我有一个视图模型的ObservableCollection,我想绑定到同一个视图的倍数,但是我只想在ObservableCollection成员不是空的情况下进行绑定,这可能吗?
<local:GenericView DataContext="{Binding GenericCollection[0]}"/>
<local:GenericView DataContext="{Binding GenericCollection[1]}"/>
<local:GenericView DataContext="{Binding GenericCollection[2]}"/>ObservableCollection是可变长度的,并不是所有成员都会出现。
发布于 2019-10-02 13:36:32
如果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}}"/>https://stackoverflow.com/questions/58202505
复制相似问题