C# 字典代码隐藏的访问控制

C# 字典代码隐藏的访问控制,c#,wpf,xaml,C#,Wpf,Xaml,在我的MainWindow.xaml中,我有一个SurfaceListBox: 但当我试图从中获取myListBox时,contentPresenter.ContentTemplate返回NULL。contentPresenter本身不为NULL。似乎Windows没有内容模板 如何从这里访问我的列表框?好的。。。已设法修改FindVisualChild以使其在访问窗口中的控件时正常工作: public static childItem FindVisualChild<childItem&

在我的MainWindow.xaml中,我有一个SurfaceListBox:

但当我试图从中获取myListBox时,contentPresenter.ContentTemplate返回NULL。contentPresenter本身不为NULL。似乎Windows没有内容模板


如何从这里访问我的列表框?

好的。。。已设法修改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");

无论您在这里尝试做什么,请使用适当的数据绑定而不是过程方法。@HighCore即使我使用数据绑定,我仍然需要访问将在主窗口中指定为myListBox源的集合对象。xaml,否?我不知道您尝试做什么,但ResourceDictionary是存储资源的工具。这些资源将由控件级或窗口级UI元素使用,而不是相反。将代码隐藏文件添加到资源字典中已经很奇怪了。你的方法真的错了。我同意这看起来很奇怪。我有一个窗口,其中包含许多不同的控件,例如,在运行时以任意数量创建和添加的图像。为了使代码更清晰,样式被写在一个单独的文件中。事实上,这张图片带有许多按钮和一个InkCanvas。为了保持代码干净,我在dict中为这些按钮和InkCanvas编写了回调。否则,它会在窗口的代码中再添加10k行,同时也不会忘记我还有很多其他控件。只是其中一个函数需要交互返回到窗口的列表框。
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);
}
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");