Search code examples
c#wpftreeview

How to add WPF treeView Node Click event to get the node value


I have a TreeView in wpf how can one get the TreeView node click event so that I can get the value of the node on which the user has clicked?

Xaml

<Grid Height="258" Width="275">
    <TreeView Height="258" HorizontalAlignment="Left" Name="treeView1" VerticalAlignment="Top" Width="275">    
    </TreeView>
</Grid>

I have populated this TreeView from the C# code. What event methode do I need to write into c# code to get the value of clicked node by the user in my c# code.

Code Behind to Load

TreeViewItem treeItem = null;
treeItem = new TreeViewItem();
treeItem.Header = "Name";

Solution

  • Since there is no Click event available for TreeViewItem or TreeView so here are possible workaround for the same

    you have two options from C# code

    using MouseLeftButtonUp which will trigger every time the mouse left button is released on the item, which is similar to click

        void preparemethod()
        {
            ...
            TreeViewItem treeItem = null;
            treeItem = new TreeViewItem();
            treeItem.Header = "Name";
            treeItem.MouseLeftButtonUp += treeItem_MouseLeftButtonUp;
        }
    
        void treeItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //your logic here
        }
    

    or use Selected as trigger, may not trigger if a selected element is clicked

        void preparemethod()
        {
            ...
            TreeViewItem treeItem = null;
            treeItem = new TreeViewItem();
            treeItem.Header = "Name";
            treeItem.Selected += treeItem_Selected;
        }
    
        void treeItem_Selected(object sender, RoutedEventArgs e)
        {
            //your logic here
        }
    

    in both of the approach the sender is the node which has been clicked. you can use as

    example

        void treeItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            //you can access item properties eg item.Header etc. 
            //your logic here 
        }