Home > Enterprise >  WPF TreeView Hide certain Items
WPF TreeView Hide certain Items

Time:07-17

I'm trying to hide some elements being displayed in the TreeView by using the Enabled property from my ViewModel. I'm setting the Visibility to Collapsed using Data Trigger, but the problem is even though the items aren't visible it just leaves those lines empty.

My XAML:

<TreeView Grid.Row="1" x:Name="ResSummTreeView" Background="Gray" ItemsSource="{Binding TreeItems}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type VM:TreeItem}" ItemsSource="{Binding Items}">
                <TextBlock Text="{Binding Header}" Margin="0 5 0 5" Foreground="Wheat" FontWeight="Bold" FontSize="15"/>
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate DataType="{x:Type VM:KeyValue}">
                        
                        <Grid Margin="0 5 5 0" x:Name="KeyValueGrid">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>

                            <TextBlock Grid.Column="0" Text="{Binding Key}" TextWrapping="Wrap" Margin="0 0 15 0" Foreground="AliceBlue"/>
                            <TextBlock Grid.Column="1" Text="{Binding Value}" HorizontalAlignment="Right" TextWrapping="Wrap" Foreground="LightGreen"/>
                        </Grid>

                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding Enabled}" Value="false">
                                <Setter TargetName="KeyValueGrid" Property="Visibility" Value="Collapsed" />
                            </DataTrigger>
                        </DataTemplate.Triggers>
                        
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

CodePudding user response:

Previously when I was hiding it from the XAML the tree header didn't collapse everytime the item is disabled. But with this approach the whole tree is closed everytime I update. Is there any solution to this ?

The solution is to add and remove items from the existing ObservableCollection<T> instead of creating a new one as this will cause the control in the view to be reset.

  • Related