Martin
Martin

Reputation: 1536

ListView Visible if multiple rows

How do I bind the ListViews visibility to a calculation? I want the Listviews to be visible ONLY if there are more than one record in the DataContexts Collection (IEnumerable)

Upvotes: 0

Views: 100

Answers (3)

RockThunder
RockThunder

Reputation: 146

Bind the visibility of the list view to the collection through a converter like so

<ListView x:Name="listView" 
ItemsSource="{Binding CollectionWithObjectsIn}" 
Visibility="{Binding CollectionWithObjectsIn, Converter={StaticResource      
 CollectionCountToVisibilityConverter}}"/>

In the CollectionCountToVisibilityConverter you have to create, you would then check the count of items in the Collection passed in and then return the correct Visibility value

Upvotes: 1

oddparity
oddparity

Reputation: 436

You could bind the Visibility to HasItems:

<Style>
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=myList, Path=HasItems}" Value="False">
            <Setter Property="UIElement.Visibility" Value="Collapsed" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Upvotes: 0

stukselbax
stukselbax

Reputation: 5935

You can create a property CollectionAny on a ViewModel, which will call IEnumerable.Any() method. You can return Visibility directly from your ViewModel, but it is not recommended by MVVM pattern. So you are able to use converter, such as BooleanToVisibilityConverter. If you can wrap your collection to a ICollecitionView interface, you can use its IsEmpty property. If it is your choice - you do not need to raise PropertyChanged event.

Here example of binding boolean property to Visibility:

<!-- Inside your resources define the converter instance -->
<BooleanToVisibilityConverter x:Key="B2VConverter">
...

<ListView 
    ...
    Visibility="{Binding Path=CollectionAny, Converter={StaticResource B2VConverter}}" 
    ...
/>

Upvotes: 1

Related Questions