Search code examples
uwpuwp-xamlwinui

Make a single TreeViewNode non-selectable


I'm trying to make the root TreeViewNode of my WinUI TreeView to act as a non-selectable "folder" for its selectable child nodes. However, the SelectionMode property is available only for the whole TreeView and not separate instances of TreeViewNode.

How can I disable selection of a single node, while still keeping it enabled for the expand/collapse functionality?


Solution

  • How can I disable selection of a single node, while still keeping it enabled for the expand/collapse functionality?

    If we just simply set the node's IsEnabled property as false, it could suit for your scenario, but it will also disable expand/collapse functionality. So we need implement expand/collapse functionality independently. We could bind TreeViewItem IsExpanded property with bool value, and use it to expand/collapse the node.

    <DataTemplate x:Key="FolderTemplate" x:DataType="local:ExplorerItem">
        <TreeViewItem
            AutomationProperties.Name="{x:Bind Name}"
            IsEnabled="False"
            IsExpanded="{Binding ElementName=MyTreeView, Path=DataContext.IsOpen, Mode=OneWay}"
            IsSelected="{x:Bind IsSelected, Mode=TwoWay}"
            ItemsSource="{x:Bind Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Source="../Assets/folder.png" />
                <TextBlock Margin="0,0,10,0" />
                <TextBlock Text="{x:Bind Name}" />
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>
    

    code behind.

    private bool _isOpen;
    public bool IsOpen
    {
        get
        {
            return _isOpen;
        }
    
        set
        {
            _isOpen = value;
            NotifyPropertyChanged("IsOpen");
        }
    
    }
    

    Usage

     IsOpen = true;