开发者

Silverlight 3 - Find Element inside items control

I have an ItemsControl that is bound to a collection of objects. Each object has it's own collection as well as other vital propert开发者_运维问答ies. To display the objects within an object, I'm displaying a TreeView inside of a ItemsControl. I know this sounds crazy. But, this is just a trimmed down version of what I am trying to accomplish to keep the question focused on the problem. Here is my sample:

<ItemsControl x:Name="myItemsControl">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <controls:TreeView x:Name="myTreeView">
      </controls:TreeView>
    </DataTemplate>                                     
  </ItemsControl.ItemTemplate>                                        
</ItemsControl>

When a user clicks a button, I need to retrieve the current TreeView associated with a specific object. In an attempt to do this, I am trying the following:

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  
  }
}

The code snippet above shows where I am trying to get the TreeView. How do I get the TreeView when looping through the items in an itemscontrol?

Thank you!


You need to use the VisualTreeHelper.GetChild and VisualTreeHelper.GetChildrenCount methods to iterate through the view's children until you find the tree that corresponds to your item. You should be able to check the TreeView.DataContext property against your item to verify its the right one. Note, you need to use this recursively as GetChild only retrieves immediate children.

As you'd need to iterate the visual tree anyway, I recommend abandoning your current loop and instead, just looping the children, checking the ID of their data contexts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜