Reputation: 43
I have a ObservableCollection of Viewmodels that I want to bind to multiples of the same view but I only want to do the binding if the ObservableCollection member is not null is this possible?
<local:GenericView DataContext="{Binding GenericCollection[0]}"/>
<local:GenericView DataContext="{Binding GenericCollection[1]}"/>
<local:GenericView DataContext="{Binding GenericCollection[2]}"/>
The ObservableCollection is of variable length and not all members will be present.
Upvotes: 1
Views: 276
Reputation: 169270
If GenericCollection[x]
is null
, there is nothing to bind to. If you want to check whether GenericCollection[x]
is null
, or don't have an item at all at index x
, you could use a converter that returns Binding.DoNothing
in case there is no collection.
Something like this:
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}}"/>
Upvotes: 2