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

2

1

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

Julissajulita answered 22/7, 2014 at 10:44 Comment(0)
E
1

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();
   }
}
Escarp answered 22/7, 2014 at 11:49 Comment(0)
F
0

I just got the following code to work. The sender ended up being the entire TreeView control, not just the selected TreeViewItem.

private void treeS3Items_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    System.Windows.Controls.TreeView s3Tree = sender as System.Windows.Controls.TreeView;
    System.Windows.Controls.TreeViewItem treeS3Item = s3Tree.SelectedItem as System.Windows.Controls.TreeViewItem;

    MessageBox.Show($"You clicked on [{treeS3Item.Header}]");
}
Fossorial answered 14/2, 2023 at 22:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.