tags:

views:

299

answers:

2

I'm using a TreeView to let the user navigate a complex data structure more easily. I'm trying to add a feature to my application so my users can add new items to the datastucture by clicking a button on a toolbar. This new item has 3 levels, each with 1 item. I would like to select the item in the lowest level.

Adding the data isn't a problem, I just add a new item to the collection that is bound to the TreeView in a specific. I can lookup the item by hand browsing the TreeView, so I know the adding works. Now, I want to set the selection of the new item programmaticly. So the user can change the default settings in the element right away.

I've done some testing and I've found that setting the selection is done with something like:

var obj = TreeView.ItemContainerGenerator
              .ContainerFromItem(selectedObject) as TreeViewItem;
obj.IsSelected = true;

I've tried adding this code directly after my Add-method. The adding function returns the new object and places this in selectedObject. The Add-method adds a to an ObservableCollection, which raises the appropriate events.

But, obj is always null directly after adding.

I've tried setting the selection in the LayoutUpdated event, but in this case the obj variable from the earlier code always null again.

I think I might be missing something here. Does anyone have an idea on how to add a new item to the bounded collection and select that item in the TreeView?

+2  A: 

You might want to read this article by Josh Smith on using the treeview in WPF. He demonstrates how to use an IsSelected property that could easily be adapted for your needs, using the MVVM pattern.

Pete OHanlon
+2  A: 

I've found a solution to this problem. Bea Stollnitz has a great article on her blog about solving this kind of problems, selecting and expanding items in a TreeView. How can I expand items in a TreeView? – Part III was the one that did it for me.

Sorskoot