Florin M
Florin M

Reputation: 445

Is there a way to hide a ListView in xaml?

I have following problem. My ListView has a gray background and when the ListView is empty, you can see a small gray line on the window. This looks ugly and so I want to hide the whole ListView when it is empty to avoid this.

I searched if there is a style property to do this, but the only stuff I found is how to hide a ListViewItem or the ListViewHeader. Has someone an idea to solve this, there has to be something.

Upvotes: 1

Views: 2270

Answers (2)

toadflakz
toadflakz

Reputation: 7944

Create a Converter that returns Visibility.Collapsed when your ItemsSource referenced collection is empty.

For example:

<ListView ItemSource="{Binding MyCollection}" Visibility="{Binding MyCollection, Converter={StaticResource EmptyCollectionConverter}}"/>

Your IValueConverter.Convert() implementation would look something like:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{
    var coll = value as IEnumerable<object>;
    return (coll.Count() > 0) ? Visibility.Visible : Visibility.Collapsed;
}

UPDATE: From another answer on how to bind to Collection.Count using a Style:

<YourControl.Style>                     
  <Style TargetType="YourControl">
    <Setter Property="Visibility" Value="Collapsed" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding MyList.Count}" Value="0">
            <Setter Property="Visibility" Value="Visible" />
        </DataTrigger>
    </Style.Triggers>
  </Style>
</YourControl.Style>

Upvotes: 4

Christophe
Christophe

Reputation: 354

<ListView ItemSource="{Binding MyCollection}">
 <ListView.Style>
   <Style TargetType="ListView">
     <Style.Triggers>
       <Trigger Property="HasItems" Value="False">
         <Setter Property="Visibility" Value="Collapsed"></Setter>
       </Trigger>
     </Style.Triggers>
   </Style>
 </ListView.Style>

 ...

</ListView>

Upvotes: 2

Related Questions