How do I hide expander in Hierarchical Data Template when all children are collapsed or hidden?

StackOverflow https://stackoverflow.com/questions/23156393

  •  05-07-2023
  •  | 
  •  

سؤال

I Have a tree view set up like so:

<TreeView ItemsSource="{Binding TreeRoot}" x:Name="HierarchyTreeView">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}>
            <Setter Property="Visibility" Value="{Binding IsVisible, Converter={...}}" />
            ...
        </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" ... />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Users have the ability to hide items in the treeview. However, when all items' visibility under a node has been set to Collapsed or Hidden, the expander remains.

Is there any way to hide the expander when every child's visibility under an item is set to hidden or collapsed?

هل كانت مفيدة؟

المحلول

I was facing this issue and came across this question. I saw there were some answers where you needed to make this change in the treeview item style which required you to edit the default style. However, like the case above I too just needed the expander to be not visible when the node items are hidden. A simple way to do it is to expand all your nodes by default and use a property in the datatrigger for the treeviewItem style to set the treeview item visibility. This is how I was able to achieve it.

<Style x:Key="myTreeItemtyle" TargetType="{x:Type TreeViewItem}">
        <Setter Property="IsExpanded" Value="True"/>     
        <Style.Triggers>
          <DataTrigger Binding="{Binding IsVisible}" Value="True">
            <Setter Property="Visibility" Value="Visible"/>
          </DataTrigger>
          <DataTrigger Binding="{Binding IsVisible}" Value="False">
            <Setter Property="Visibility" Value="Collapsed"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>

Now, use this style as the treeview item container style:

<TreeView Name="treeView" ItemsSource="{Binding TreeItems}" ItemContainerStyle="{StaticResource myTreeItemtyle}" BorderThickness="0"/>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top