I have a ListView
using a WrapPanel
as its ItemsPanel
, and I use ListViewItem
directly as content. But when one ListViewItem.Visibility
is Collapsed
, you can still see the space it's using.
First off, a sample XAML code similar to what I use :
<Grid>
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Hidden" ItemContainerStyle="{DynamicResource ContainerStyle}">
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}" x:Key="ContainerStyle">
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.Resources>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel ItemHeight="200" ItemWidth="200"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListViewItem Margin="10" Visibility="Visible">
<Border Background="Red"/>
</ListViewItem>
<ListViewItem Margin="10" Visibility="Visible">
<Border Background="Blue"/>
</ListViewItem>
<ListViewItem Margin="10" Visibility="Visible">
<Border Background="Green"/>
</ListViewItem>
</ListView>
</Grid>
For example, when all items are visible (code above) I have this :
But if I change the first item to make it collapsed as follows
<ListViewItem Margin="10" Visibility="Collapsed">
<Border Background="Red"/>
</ListViewItem>
What I would expect would be the following :
As such I don't understand why it is acting like this, the Collapsed
seems to behave just like Hidden
. I'm applying it directly to the item and don't see what else to do .
I've tried different solutions I found, most notably this one about binding to Visibility in the style and this one going more or less in the same direction but without success, same results.
The accepted answer actually does not provide a solution, which is instead delivered in its comment section.
If you set ItemWidth, WrapPanel will reserve the ItemWidth for all the items bound to itself, visible or not.
The workaround here is not to set ItemWidth on the WrapPanel but set the Width on the ItemTemplate.
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel MinWidth="96" />
</DataTemaplate>
</ItemsControl.ItemTemplate>