how to properly expand a TreeViewItem in avalonia

309 views Asked by At

I have a user control with a tree view with data template.

I fill the tree view in a constructor like this:

        var works = new WorksTreeViewItem();
        var world = new WorldTreeViewItem
            {
                            // ...
            };

        WorldOrWorksTreeViewItems = new ObservableCollection<WorldOrWorksTreeViewItem>
        {
            world,
            works
        };
        

How can I set the world treeViewItem expanded?

I have tried expand each treeVeiwItem at least with this code in TreeView in xaml:

<Style Selector="TreeViewItem">
      <Setter Property="IsExpanded" Value="True"/>
</Style>

but after that, the treeView has only one item with text: treeviewitem

2

There are 2 answers

0
Belafon On

I have found out, that I can use this:

   <TreeView.ItemContainerTheme>
      <ControlTheme TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
        <Setter Property="IsExpanded" Value="True" />
      </ControlTheme>
    </TreeView.ItemContainerTheme>

But that expands everything and I want to expand just some of them.

I guess I should use x:Key, but it doesnt want to compile, even if that is what I have found in the official website for ControlTheme.

0
Thomas Joshua On

You can bind the IsExpanded to a bool property in the treeview item's viewmodel, and set its mode to TwoWay binding. And you can now set the IsExpanded from code behind in the view model.

For example, create a TreeViewItemViewModel class with a new boolean property called _isExpanded marked with [Observable Property] (using community toolkit MVVM). Then if you like to use it for example, in your MainView.axaml. You can set the style like this.

<TreeView>
    <TreeView.Styles>
        <Style Selector="TreeViewItem" x:DataType="vm:TreeViewItemViewModel">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
        </Style>
    </TreeView.Styles>
</TreeView>