在Xamarin Forms中将列表视图项数绑定到标签可见性

5
我在Xamarin Forms中绑定方面遇到了问题。我想根据Listview的项目数将LabelIsVisible属性设置为true/false。如果Listview有任何项目,那么Label IsVisible将为false,否则将为true。在Xamarin Forms中使用绑定是否可行?我尝试过,但是我不知道如何在XAML中将数字0转换为boolean false。请帮我修改一下。

你能分享一下你已经写的代码吗?关于XAML和代码后台。 - Esteban Verbel
3个回答

11

您可以纯粹使用XAML和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>

处理按钮点击并初始化列表内容的代码(通常我使用数据绑定,但为了在示例中简化,我使用了代码后台):

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");
    }
  }
}

绑定到 Count 属性可行是因为 ItemsSource 是一个 ObservableCollection


4
当然是可以的。我假设您已经有一种方法来获取ListView中项目的数量,以下是如何将该数字转换为XAML中的布尔值。
您需要的是IValueConverter接口的自定义实现。它可以接受绑定提供的值并将其转换为其他内容(如果需要,则可进行返回)。
在您的情况下,您想要取一个整数并返回一个布尔值。如果该值为零,则返回true,否则返回false。
public class CountToBoolenConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {            
        return (int)value != 0;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }
}

接下来,您需要在XAML中定义命名空间。在文件顶部,您应该添加类似于以下内容的东西:

xmlns:local="clr-namespace:YourNameSpace;assembly=YourAssembly"

将转换器添加到页面资源中,在开头的<ContentPage>标签(或您拥有的任何类型的页面)之后:
<ContentPage>
  <ContentPage.Resources>
    <ResourceDictionary>
      <CountToBoolenConverter x:Key="countToBoolean" />
    </ResourceDictionary>
  </ContentPage.Resources>

  <!-- Rest of the page -->

最后,使用转换器将IsVisible属性设置为您的标签:

<Label IsVisible="{Binding ItemCount, Converter={StaticResource countToBoolean}}">

ItemCount是您的视图模型中的整数属性,应包含ListView项目的计数。您可能已经有一种加载ListView项目集合的方法,因此应该很容易确定应如何完成此属性。


@vamteusz 没问题!如果这解决了你的问题,请随意将其标记为答案。 :) - Timo Salomäki

0
尝试这个:
XAML
   <StackLayout>
        <Label Text="Welcome to Xamarin Forms!" IsVisible="{Binding ShowLabel}">
        </Label>
        <ListView x:Name="TheListView" />

        <Button x:Name="btnAddItem" Text="Add an item" Clicked="btnAddItem_Clicked"   />
    </StackLayout>



 public partial class MainPage : ContentPage, INotifyPropertyChanged
    {
public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<string> _items = new ObservableCollection<string>();

    public bool ShowLabel
    {
        get
        {
            return !(Items.Count > 0);
        }
    }

    public ObservableCollection<string> Items
    {
        get { return _items; }

        set
        {
            _items = value;

        }
    }

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

    private void btnAddItem_Clicked(object sender, EventArgs e)
    {
        Items.Add("Add a item");
        NotifyPropertyChanged("ShowLabel");            
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接