在我的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?
答案 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");