How do I listen to click events on all the tree nodes through the parent tree?

Platform: WPF| Category: TreeView

Instead of setting up event handlers on all the tree nodes you can listen to those events as they bubble up to the tree as follows:

[XAML]

<TreeView TreeViewItem.Selected="TvItem_Selected">
<TreeViewItem>Node1</TreeViewItem>
<TreeViewItem>Node2</TreeViewItem>
<TreeViewItem>Node3</TreeViewItem>
<TreeViewItem>Node4</TreeViewItem>
</TreeView>

Or you can setup the same thing in code as follows:

[C#]
treeView1.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(TvItem_Selected));

The event handler would then be something like:

private void TvItem_Selected(object sender, RoutedEventArgs e)
{
	TreeViewItem item = e.Source as TreeViewItem;
            
	....
}

Share with