tags:

views:

117

answers:

1

I have got an Indexer property in a Class called X, suppose X[Y] gives me a another object of Type Z

<ContentControl Content="{Binding X[Y]}" ...???

How can I make a DataBinding happens inside indexer? It works if I do {Binding [0]} . But {Binding X[Y]} just takes the indexer parameter as a string which is "Y"

Update : Converter is an option, But I have plenty of ViewModel classes with indexer and doesnt have similar collection, So I cant afford to make seperate converters for all those.So I just wanted to know this is supported in WPF if yes, how to declare Content=X[Y] where X and Y are DataContext properties?

+1  A: 

The only way I've found to accomplish this is through a MultiBinding and a IMultiValueConverter.

<TextBlock DataContext="{Binding Source={x:Static vm:MainViewModel.Employees}">
    <TextBlock.Text>
       <MultiBinding Converter="{StaticResource conv:SelectEmployee}">
           <Binding />
           <Binding Path="SelectedEmployee" />
       </MultiBinding>
    </TextBlock.Text>
</TextBlock>

And your converter:

public class SelectEmployeeConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, 
        object parameter, CultureInfo culture)
    {
        Debug.Assert(values.Length >= 2);

        // change this type assumption
        var employees = values[0] as ICollection<Employee>;
        var index = Convert.ToInt32(values[1]);

        // and check bounds
        if (employees != null) return employees[index];

        return Binding.DoNothing;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
sixlettervariables
Yeah thanks and this is the obvious solution if there is only one class. But I have plenty of ViewModel classes similar to this So I cant afford having seperate converters, Instead I change the Indexer logic to something else.
Jobi Joy