Question

How can I expand a node in a treeview using MVVM?

I have a x level treeview and I made my own class to bind it to the TreeView control.

I did manage to set IsSelected property to true when I create the TreeView list. So I just have to bind my IsSelected value to the TreeViewItem IsSelected property, but it's not that simple at all...

Here is my class:

public class HierarchicalItem : Model
{
    public string Name { get; set; }
    public int Id { get; set; }

    private bool _IsSelected;
    public bool IsSelected
    {
        get { return _IsSelected; }
        set
        {
            if (_IsSelected != value)
            {
                _IsSelected = value;
                RaisePropertyChanged("IsSelected");
            }
        }
    }

    private ObservableCollection<HierarchicalItem> _children;
    public ObservableCollection<HierarchicalItem> Children
    {
        get
        {
            return _children;
        }
        set
        {
            if (_children != value)
            {
                _children = value;
                RaisePropertyChanged("Children");
            }
        }
    }
}

I tried that with IsSelected and IsExpanded:

<controls:TreeView.ItemContainerStyle>
    <Style TargetType="controls:TreeViewItem">
        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
    </Style>
</controls:TreeView.ItemContainerStyle>

But it returns, that IsSelected and IsExpanded is read only (this works in WPF).

I have looked many solutions for this, but none works for me, because I have dynamic treeviews in a listbox and in each of the treeviews I have to expand the whole path to the node that has a given Id. For example I want to expand all nodes that have Id = 30 in each treeview.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top