WPF - hiding listbox items WPF - hiding listbox items wpf wpf

WPF - hiding listbox items


You are succesfully hiding your item, however, the ListBox wraps each of your items within a ListBoxItem, this adds concepts such as selection to your item. I suspect you are still seeing the ListBoxItem in the case where your items are hidden. You can use the ItemContainerStyle to hide ListBoxItems ...

<ListBox>  <ListBox.ItemContainerStyle>    <Style TargetType="{x:Type ListBoxItem}">      <Style.Triggers>        <DataTrigger Binding="{Binding IsActive}" Value="False">          <Setter Property="Visibility" Value="Collapsed"/>        </DataTrigger>      </Style.Triggers>    </Style>  </ListBox.ItemContainerStyle></ListBox>


This can also be achieved by populating ListBox.Items only with ListBoxItem instead of other controls:

ListBox.Items.Add(new ListBoxItem {     Content = new CheckBox {Content = "item 1"}     })

or

<ListBox>    <ListBox.Items>        <ListBoxItem>            <CheckBox Content="item 1"/>        </ListBoxItem>    </ListBox.Items></ListBox>

Then in the code behind or in the trigger, you can hide the items directly:

ListBox.Items[0].Visibility = Visibility.Collapse

This will hide the item as well as the 4px border. This method gives you control of visibility for each individual item.


I went with ColinE's proposed solution. Here is a full snipped for everybody's convenience. Thanks ColienE.

      <ListBox ItemsSource="{Binding Properties}" Height="110">            <ListBox.ItemTemplate>                <HierarchicalDataTemplate>                    <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" Visibility="{Binding Visible}" />                </HierarchicalDataTemplate>            </ListBox.ItemTemplate>            <ListBox.ItemContainerStyle>                <Style TargetType="{x:Type ListBoxItem}">                    <Style.Triggers>                        <DataTrigger Binding="{Binding Visible}" Value="Collapsed">                            <Setter Property="Visibility" Value="Collapsed"/>                        </DataTrigger>                    </Style.Triggers>                </Style>            </ListBox.ItemContainerStyle>      </ListBox>