2017-09-04 30 views
2

我在Xamarin Forms中绑定有问题。根据Listview的计数项目,我想将的IsVisible财产设置为true/false。如果Listview有任何项目,Label IsVisible将为false,否则将为true。有没有可能在Xamarin表单中进行绑定?我试图做到这一点,但我不知道如何在XAML中将0号码转换为boolean false绑定列表视图项目计数到Xamarin表单中的标签可见性

+0

您可以分享您迄今为止编写的代码吗?在XAML和代码背后 –

回答

2

当然有可能。我假设你已经有了一种获取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 --> 

而且然后最后使用转换器的可见性属性设置为您的标签:

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

ItemCount中是在你的视图模型整数属性,它应该包含的数ListView项目。您可能已经有了一种为ListView加载项目集合的方法,因此应该弄清楚该属性应该如何完成。

+0

非常感谢! – vamteusz

+0

@vamteusz没问题!如果能解决您的问题,请随时将其标记为答案。 :) – hankide

1

你可以纯粹用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> 

代码隐藏处理按钮点击并初始化列表中的内容(我通常使用data binding,但在我的例子简单使用代码隐藏):

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属性的绑定工作,因为ItemsSourceObservableCollection

相关问题