作为起点,我的测试项目是Xamarin表单选项卡项目 - 来自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,以使用转换器。
。 <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中,我添加了itemproperty:
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);
这不起作用。转换器接收零。我需要的是转换器使用项目ViewModel的observableCollection:
public ObservableCollection<Item> Items { get; set; }
我如何在XAML中签订绑定以使用havitemsconverter从itemsViewModel检索列表并返回用于启用或禁用列表的bool?
原因:
Source={x:Reference BrowseItemsPage}
设置源时,BindingContext
将同时更改;
解决方案:
什么是BrowseItemsPage
?如果是您的ViewModel,则应在ContentPage(hotherwise(中设置 bindingContext ,只是使用
IsEnabled="{Binding Items, Mode=OneWay , Converter={StaticResource HaveItemsConverter}}
我没有得到您的代码的完整范围,这就是为什么我提供简单快速的解决方案,添加更多属性,例如项目,
bool _itemsAvailable;
Public bool ItemsAvailable
{get {return _itemsAvailable;}}
{set {_itemsAvailable=value; RaisePropert....}}
并在您的ObservableCollection set 下设置上述Bool变量,如下所示,
public ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get
{
return _items;
}
set
{
_items = value;
if(_items!=null && _items.Count>0)
{
ItemsAvailable = true;
}
}
}
并绑定可见属性的此项目属性,并删除不需要的转换器。快乐编码:(