Search code examples
c#wpftreeview

Getting the value of the Selected Child Nodes on click Event in WPF TreeView


I have a TreeView in WPF Which contains One Main Node and 5 Child Node.As soon as Main Node is expanded we get child Nodes.Now on Expanding child node we get some Values.This is the representation of my treeView In WPF.In this one i want to get the Value of one of the 5 Child Node that has been expanded.

Here is the code that i am trying ..

void getTreeView()
{

    TreeViewItem treeItem = null;
    treeItem = new TreeViewItem();
    treeItem.Header = "Name";
    treeItem.MouseLeftButtonUp += treeItem_MouseLeftButtonUp;
}

void treeItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
   TreeViewItem item = sender as TreeViewItem;
   foreach(TreeViewItem child in item.Items) { 

       string childNode=child.Header as string;


 }
}

But here in childNode i am getting the value of the all 5 child node whereas i need to that of the selected ones.

Please help me


Solution

  • If you want to get only selected node, check for IsSelected property of TreeViewItem like this:

    foreach(TreeViewItem child in item.Items) 
    { 
       if(child.IsSelected)
       {
          string childNode= child.Header.ToString();
       }
    }