简体   繁体   中英

Get the Selected Tree View Item

I am using a wpf tree in a .net form. So, I don't have any xaml. I simply do everything in code. I am using Hierarchical Data Template to bind my data to the wpftree.

I am trying to find a way to get the TreeViewItem for the Node selected in the tree. I tried registering a EventHandler on the SelectedItemChanged event on the TreeView, but in that handler I only get the associated data object. Since my tree is virtual, ItemContainerGenerator.ContainerFromItem doesn't work.

When I searched on StackOverflow, one suggestion was to listen to the TreeViewItem.Selected event. But I couldn't find a way to do this in code. ( I don't have a xaml).

Any help is greatly appreciated.

thank you.

What you could do is attach the handler to each control every time you add it

void AddTreeViewItem()
{
    TreeView t = new TreeView();
    TreeViewItem treeItem = new TreeViewItem();
    t.Items.Add(treeItem);

    treeItem.Selected += DoSomethingHere;
}

private void DoSomethingHere(object sender, RoutedEventArgs e)
{
    Console.WriteLine("Tree Item Selected");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM