首先,我的测试项目是Xamarin Forms Tab项目-来自Xamarin模板。
我有一个转换器:
using System;
using System.Collections;
using System.Globalization;
using Xamarin.Forms;
namespace TabExample.Converters
{
public class HaveItemsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is ICollection)
{
return ((ICollection)value).Count > 0;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
我已将其添加到App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:TabExample.Converters"
x:Class="TabExample.App">
<Application.Resources>
<ResourceDictionary>
<!-- Converters -->
<converters:HaveItemsConverter x:Key="HaveItemsConverter"/>
<!--Global Styles-->
<Color x:Key="NavigationPrimary">#2196F3</Color>
<Style TargetType="NavigationPage">
<Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" />
<Setter Property="BarTextColor" Value="White" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
我已经使用转换器将ItemsPage.xml中的ListView更新为添加IsEnabled。
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected"
IsEnabled="{Binding Items, Mode=OneWay, Converter={StaticResource HaveItemsConverter}, Source={x:Reference BrowseItemsPage}}">
在ItemsPage.xaml.cs中,我添加了ItemsProperty:
public List<Item> Items
{
get { return (List<Item>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly BindableProperty ItemsProperty =
BindableProperty.Create("Items", typeof(List<Item>), typeof(ItemsPage), null, BindingMode.OneWay);
这不起作用。转换器收到空值。我需要的是转换器,以便使用ItemsViewModel中的Items ObservableCollection:
public ObservableCollection<Item> Items { get; set; }
我如何在Xaml中属性绑定挂钩,以使用HaveItemsConverter从ItemsViewModel检索列表并返回用于启用或禁用列表的布尔值?
答案 0 :(得分:0)
原因:
Source={x:Reference BrowseItemsPage}
设置Source时,BindingContext
将同时更改;
解决方案:
BrowseItemsPage
是什么?如果是您的视图模型,则应在contentPage中设置 BindingContext ,否则只需使用
IsEnabled="{Binding Items, Mode=OneWay , Converter={StaticResource HaveItemsConverter}}
答案 1 :(得分:0)
我没有获得完整的代码范围,这就是为什么我要提供简单快捷的解决方案,并添加另一个属性,例如ItemsAvailable,
bool _itemsAvailable;
Public bool ItemsAvailable
{get {return _itemsAvailable;}}
{set {_itemsAvailable=value; RaisePropert....}}
然后在您的Observablecollection下设置上述bool变量 Set ,如下所示,
public ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get
{
return _items;
}
set
{
_items = value;
if(_items!=null && _items.Count>0)
{
ItemsAvailable = true;
}
}
}
并将此ItemsAvailable属性绑定为您的可见属性,并删除不需要的转换器。 编码愉快:)