1
votes

I have model objects set up like so:

public class Model
{
    public ObservableCollection<Model> Children{get;set;}
    public string Name{get;set;}
}

This gives me a tree of model objects of arbitrary size and depth. I display these in a WPF TreeView using a hierarchical datatemplate. Because of the ObservableCollection, I can add model objects anywhere in the model tree and the UI will update accordingly.

The annoyance comes because even though a new model object might be added at the third level, for example, it might not be immediately visible.

When a new model object is added anywhere in the tree, I would like the TreeView to automatically select the new node, and expand its parents to that it is immediately visible to the user. This doesn't seem to be immediately obvious.

What I don't want to do is pollute the Model objects with properties which only make sense in a particular WPF control. Nor do I want to add a parent property to the Models.

It seems that this must have been tackled before by someone. Does anyone have an idea on how to tackle this?

1

1 Answers

1
votes

Create 2 properties in your model as below IsExpanded and IsSelected

and in your treeview ItemContainerStyle add the below setters

<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
<Setter Property="IsExpanded" Value="{Binding IsExpanded}"/>

Noe everytime you set these 2 properties in your viewmodels, the corresponding treeviewitem will be selected/expanded