Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Listview Item Count to Label Visibility in Xamarin Forms

I have a problem with binding in Xamarin Forms. I want to set IsVisible property of Label to true/false according of count items of Listview. If Listview have any items, Label IsVisible will be false, otherwise will be true. Is it possible to make in Xamarin Forms with binding? I tried to do this but I don't know how to convert number 0 to boolean false in XAML.

like image 824
vamteusz Avatar asked Sep 04 '17 18:09

vamteusz


1 Answers

You can do it purely in XAML using a DataTrigger:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="ListViewTriggerToHideLabel.MainPage">
    <StackLayout>
        <Label Text="Welcome to Xamarin Forms!" IsVisible="False">
            <Label.Triggers>
                <DataTrigger TargetType="Label"
                             Binding="{Binding Source={x:Reference TheListView}, Path=ItemsSource.Count}" 
                             Value="0">
                    <Setter Property="IsVisible" Value="True" />
                </DataTrigger>
            </Label.Triggers>
        </Label>
        <ListView x:Name="TheListView" />
        <Button Text="Add an item" Clicked="Button_OnClicked" />
    </StackLayout>
</ContentPage>

The code-behind to handle button clicks and initialise the list content (I normally use data binding, but for simplicity in the example I'm using code-behind):

using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace ListViewTriggerToHideLabel {
  public partial class MainPage : ContentPage {
    private readonly ObservableCollection<string> _items = new ObservableCollection<string>();

    public MainPage() {
      InitializeComponent();
      TheListView.ItemsSource = _items;
    }

    private void Button_OnClicked(object sender, EventArgs e) {
      _items.Add("Ouch");
    }
  }
}

The binding to the Count property works because the ItemsSource is an ObservableCollection.

like image 180
Damian Avatar answered Oct 05 '22 23:10

Damian