简体   繁体   中英

WPF: Not able to get TreeViewItem from the SelectedItem

I am using HierarchicalDataTemplate to form the tree. I am doing the following things: 1. Select a folder and click on "Add Folder" button. 2. A new folder under a selected folder should be shown. The ViewModel is updated correctly such that it has a Folder under the selected folder element and the same is updated in the TreeView.

My concern is how do I get the TreeViewItem of the added folder. I have the reference to the newly added folder but don't know how to get the TreeViewItem of the same. Below is the sample code that adds the folder

ElementFolder folder = ViewModel.AddFolder(selectedFolder, "NewFolder");
Here, folder is the reference to the new folder added of type ElementFolder . The ItemsSource of the HierarchicalDataTemplate is ElementFolder .

Please help. I am stuck. Read many posts but none came to my rescue. Please help !! I tried the ideas mentioned in this link but it did not help : How to get TreeViewItem from HierarchicalDataTemplate item?

Here is how I made it work

  1. Set the ItemsContainerStyle of the TreeView such that a Handler is invoked whenever a TreeViewItem is selected. This can be achieved via EventSetter binding ie set a handler for Selected event.
  2. Create binding for TreeViewItem's IsSelected property to a IsFldrSelected property created in my ViewModel.
    Note: Requires a TwoWay binding for this
  3. Whenever a new folder is added to the tree (Refer sample code on how I am adding folder), I have reference to that folder. Using this reference I set the IsFldrSelected property of folder object to true .
  4. Upon doing this IsSelected property of the newly added TreeViewItem is set to true. (Basically this will select the TreeViewItem programatically).
  5. This will fire the Selected event which in turn will invoke it's handler where the sender will be the selected TreeViewItem that I needed.

Note: The moment you get the required TreeViewItem, set the Handled property of RoutedEventArgs to true ( e.Handled = true ) otherwise this handler will be called multiple times till the root of the tree is reached (this is because of bubbling event) due to which you will lose the TreeViewItem that is required.

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