我有一个ItemsControl绑定到一组对象。每个对象都有自己的集合以及其他重要属性。要显示对象中的对象,我在ItemsControl中显示TreeView。我知道这听起来很疯狂。但是,这只是我想要完成的一个精简版本,以便将问题集中在问题上。这是我的样本:
<ItemsControl x:Name="myItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:TreeView x:Name="myTreeView">
</controls:TreeView>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
当用户单击按钮时,我需要检索与特定对象关联的当前TreeView。为了做到这一点,我尝试以下方法:
MyClass instanceToFind = (MyClass)(IdentifyDesiredInstance());
foreach (MyClass instance in myItemsControl.Items)
{
if (instance.ID == instanceToFind.ID)
{
TreeView treeView = null; // How do I get the TreeView?
// Do other necessary updates
}
}
上面的代码片段显示了我尝试获取TreeView的位置。在循环遍历itemscontrol中的项目时如何获取TreeView?
谢谢!
答案 0 :(得分:3)
您需要使用VisualTreeHelper.GetChild
和VisualTreeHelper.GetChildrenCount
方法迭代视图的子项,直到找到与您的项目对应的树。您应该可以针对您的商品检查TreeView.DataContext
属性,以验证其是否正确。注意,您需要递归使用此函数,因为GetChild
仅检索直接子项。
因为你需要迭代可视化树,我建议放弃你当前的循环,而只是循环子节点,检查它们的数据上下文的ID。