字典代码背后的访问控制

时间:2014-03-11 03:03:27

标签: c# wpf xaml

在我的MainWindow.xaml中,我有SurfaceListBox

<SurfaceListBox x:Name="myListBox" />

在我的资源字典(myDictionary.xaml)的CS文件( myDictionary_CallBack.cs )中,我需要对myListBox做一些事情。我该如何访问它?

到目前为止,我已经尝试过:

private void doWork(ScatterViewItem svi) //in myDictionary_CallBack.cs
{
    Window mainWindow = GetVisualAncestor<Window>(svi);
    SurfaceListBox myListBox = GetChild<SurfaceListBox>(mainWindow, "myListBox");
}

GetVisualAncestor按预期返回Window。这是GetChild函数:

public static childItem GetChild<childItem>(DependencyObject obj, string elementName) where childItem : DependencyObject
{
    ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(obj);
    DataTemplate dataTemplate = contentPresenter.ContentTemplate;

    return (childItem)dataTemplate.FindName(elementName, contentPresenter);
}

但是当我尝试从中获取myListBox时,它会为contentPresenter.ContentTemplate返回NULL。 contentPresenter本身不是NULL。好像没有用于Window的contentTemplate。

如何从这里访问myListBox?

1 个答案:

答案 0 :(得分:0)

好的...设法修改FindVisualChild以使其正常工作(在窗口中访问控件):

public static childItem FindVisualChild<childItem>(FrameworkElement obj, string elementName) where childItem : FrameworkElement
{
    if (obj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var child = VisualTreeHelper.GetChild(obj, i);

            if (child != null && child is childItem && (child as childItem).Name == elementName)
                return child as childItem;
            else
            {
                childItem childOfChild = FindVisualChild<childItem>(child as FrameworkElement, elementName);

                if (childOfChild != null)
                    return childOfChild;
            }
        }
    }

    return null;
}

使用它:

SurfaceListBox myListBox = FindVisualChild<SurfaceListBox>(mainWindow, "myListBox");