[英]Updating binding for ObservableCollection member property without INotifyPropertyChanged
[英]Binding DataContext only if ObservableCollection member is not Null
我有一个 Viewmodels 的 ObservableCollection,我想绑定到同一视图的多个,但我只想在 ObservableCollection 成员不是 null 时进行绑定,这可能吗?
<local:GenericView DataContext="{Binding GenericCollection[0]}"/>
<local:GenericView DataContext="{Binding GenericCollection[1]}"/>
<local:GenericView DataContext="{Binding GenericCollection[2]}"/>
ObservableCollection 是可变长度的,并非所有成员都会出现。
如果GenericCollection[x]
是null
,则没有可绑定的内容。 如果要检查GenericCollection[x]
是否为null
,或者索引x
处根本没有项目,则可以使用返回Binding.DoNothing
的转换器,以防没有集合。
像这样的东西:
public class Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
IList genericCollection = value as IList;
int index = System.Convert.ToInt32(parameter);
if (genericCollection.Count > index)
{
object collection = genericCollection[index];
if (collection != null)
return collection;
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
XAML:
<local:GenericView DataContext="{Binding GenericCollection, ConverterParameter=1, Converter={StaticResource converter}}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.