Reputation: 187
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
Upvotes: 1
Views: 4799
Reputation: 69
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}]");
}
Upvotes: 0
Reputation: 81333
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();
}
}
Upvotes: 1