1
votes

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?

1
Does the TreeVieweItem.Selected event on your TreeView get not get fired when adding the folder to the ViewModel then?Paul Hodgson
@Paul - No. The "Selected" event does not get fired when a new folder is added to the Model (in turn a new TreeViewItem is added to the model). However, I have figured out the answer to my question. Refer my answer below.Nayan Soni

1 Answers

0
votes

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 i.e. 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.