【发布时间】:2019-09-21 02:51:51
【问题描述】:
作为起点,我的测试项目是 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 检索列表并返回用于启用或禁用列表的布尔值?
【问题讨论】:
-
为什么要在最后加上
, Source={x:Reference BrowseItemsPage}?您似乎不需要它,因为您在上面几行直接绑定了属性Items。 -
我不知道绑定需要什么,这就是问题所在。我真正需要的是绑定到 ViewModel 中的列表 - 在这种情况下,它是 ObservableCollection
- 项,而不是视图中的列表。
-
当您删除
IsEnabled属性时,项目是否显示在ListView中?如果是这样,{Binding Items}工作正常,这意味着IsEnabled="{Binding Items, Mode=OneWay, Converter={StaticResource HaveItemsConverter}}"应该可以工作。
标签: c# xaml xamarin.forms binding viewmodel