Getting TreeViewItem for the selected item in a TreeView

后端 未结 4 1362
遥遥无期
遥遥无期 2020-12-31 05:32

I have a TreeView that is bound to a dataset which is having parent child relation. How i will get seleted TreeViewItem from the TreeView? Please help me. My code is below.

4条回答
  •  一向
    一向 (楼主)
    2020-12-31 06:16

    The best solution I've found involves a simple helper method and can be used in virtually any of the TreeView's events (i.e., SelectedItemChanged, MouseLeftButtonUp, etc.).

    TreeViewItem Item = TreeViewHelper.VisualUpwardSearch(e.OriginalSource as DependencyObject);
    

    I am using multiple hierarchy data templates and this is the only method that worked for me. Now, I'm able to create a new control based on TreeView and can handle all events involving the selected item internally.

    public static TreeViewItem VisualUpwardSearch(DependencyObject source)
    {
        while (source != null && !(source is TreeViewItem)) source = System.Windows.Media.VisualTreeHelper.GetParent(source);
        return source as TreeViewItem;
    }
    

提交回复
热议问题