[英]Xamarin binding count of ItemSource
我需要使用XAML启用/禁用它,它是基于ItemsItem中元素数量的选择器。
<Picker
ItemsSource="{Binding WoSpesaDett.DsTecnico}"
ItemDisplayBinding="{Binding Valore}"
SelectedItem="{Binding WoSpesaDett.Tecnico}"
IsEnabled="{Binding ???}"
Grid.Row="0" Grid.Column="3"/>
我尝试使用WoSpesaDett.DsTecnico.Count > 0
但它不起作用。
我该如何实现?
谢谢!
IValueConverter
,将整数转换为布尔值:
public class IntToBooleanConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
{
int minimumLength = System.Convert.ToInt32 (parameter);
return (int)value >= minimumLength;
}
public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException ();
}
}
注意:
如果您只需要更改选择器的可见性一次(而不是以动态方式),则可以像其他答案指出的那样创建一个转换器。
除此以外:
从理论上讲,动态隐藏或显示UI控件非常简单。 您要做的就是在模型中引入一个布尔属性,例如:
public bool MyPickerShouldBeVisible => WoSpesaDett.DsTecnico.Count > 0;
现在的问题是,您需要将与MyPickerShouldBeVisible
相关的更改通知给View
。 我通常使用Fody.PropertyChanged处理INotifyPropertyChange
东西。 使用它,您可以使用特殊属性AlsoNotifyFor(nameof(MyPickerShouldBeVisible))
标记DsTecnico
属性,以使该解决方案起作用。
这是一个完整的示例,ViewModel数据得到了简化:
// INotifyPropertyChanged should be handled by `Fody.PropertyChanged`
public class MyViewModel : INotifyPropertyChanged
{
public IList<string> MyData { get; set; }
[AlsoNotifyFor(nameof(MyPickerShouldBeVisible))]
public bool ShouldShowPicker => MyData.Any();
}
使用上面的示例,将导致选择器的动态行为。
您可以在绑定上下文中创建布尔值:
public bool PickerShouldBeEnabled
{
get { return WoSpesaDett.DsTecnico.Count > 0; } //returns true if there are more than 0 elements
}
为了获得更好的性能,请使用linq“ Any()”,如果您只想在列表中有任何元素的情况下启用它
public bool PickerShouldBeEnabled
{
get { return WoSpesaDett.DsTecnico.Any(); } //returns true if there are any elements
}
或者,您可以创建一个IValueConverter ,该IValueConverter将列表作为值,并根据列表元素的计数返回true。 我也可以为您提供这种情况的基本转换器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.