Search code examples
c#avaloniaui

ReactiveCommand when TreeView is expanded?


The Avalonia TreeView docs give us the following XAML code for opening a TreeView of files from a directory:

<TreeView
    Items="{Binding Items}"
    Width="400" Height="480"
    HorizontalAlignment="Left">

    <TreeView.ItemTemplate>
        <TreeDataTemplate ItemsSource="{Binding Subfolders}">
            <TextBlock Text="{Binding strNodeText}" />
        </TreeDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

The docs load all subfolders upon the start of the app with the recursive GetSubFolders method. I refactored that method to an instance method of the Node class. Now, I want to only call that method on a Node if it is expanded in the TreeView, as to not have to load all the files at once. However, I can't find any way for the Node model to detect when it has been expanded in the TreeView.

How would I go about calling this method properly?


Solution

  • You can do something like this:

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

    On your class that is the ViewModel for each TreeViewItem, ensure there is a bindable property:

    public bool IsExpanded
    {
        get { return _isExpanded; }
        set { this.RaiseAndSetIfChanged(ref _isExpanded, value); }
    }
    

    Now what you could do this:

    set
    {
        if (this.RaiseAndSetIfChanged(ref _isExpanded, value))
        {
            GetSubFolders();
        }
    }