views:

122

answers:

2

I'd like to get an event for any expansion of a treeviewitem in my treeview.

The reason for this, a bit unrelated to the original question: I am creating a tree that relates closely to an xml file tree, but I am allowing an include element in the xml so the tree can go across multiple files. I'd like to set the itemssource property of treeviewitems within my treeview upon expansion.

A: 

See the Hierarchical Databinding in WPF

Sauron
+2  A: 

You can use the TreeViewItem.Expanded event as an attached event :

<TreeView TreeViewItem.Expanded="TreeViewItem_Expanded"
          ItemsSource="{Binding}">
    ...
</TreeView/>

In code-behind, you can identify the TreeViewItem that initiated the event using the OriginalSource property :

    private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
    {
        TreeViewItem tvi = e.OriginalSource as TreeViewItem;
        if (tvi != null)
        {
            MessageBox.Show(string.Format("TreeNode '{0}' was expanded", tvi.Header));
        }
    }
Thomas Levesque
if you mean the visual descendants, you can get them through the ItemsContainerGenerator of the TreeViewItem
Thomas Levesque
This was so helpful, thank you, I wish had a bounty to give you. Final summary: The visual descendents I wanted were not created yet during the expanded event. In the expansion event I saved the OriginalSource, then in an arbitrary converter method for a binding, I got the visual descendent with ItemContainerGenerator.ContainerFromIndex(i) and updated the ItemsSource.
Ian Kelling