XAML Indexer DataBinding

I have a property Indexerin a class named X, suppose it X[Y]gives me another object of type Z:

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

How can I do DataBindinginside the indexer? It works if I do {Binding [0]}. But {Binding X[Y]}just accepts the indexer parameter as a string, which Y.

Update: Converter - an option, but I have many ViewModel classes with an index and I do not have a similar collection. Therefore, I can not afford to create separate converters for all of these. So I just wanted to know that it is maintained in a WPF, if so, how to declare Content=X[Y]where Xand Yare the DataContextproperties?

+3
source share
1 answer

The only way I found for this is MultiBinding and 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 array = values[0] as Array;
        var list = values[0] as IList;
        var enumerable = values[0] as IEnumerable;
        var index = Convert.ToInt32(values[1]);

        // and check bounds
        if (array != null && index >= 0 && index < array.GetLength(0))
            return array.GetValue(index);
        else if (list != null && index >= 0 && index < list.Count)
            return list[index];
        else if (enumerable != null && index >= 0)
        {
            int ii = 0;
            foreach (var item in enumerable)
            {
                if (ii++ == index) return item;
            }
        }

        return Binding.DoNothing;
    }

    public object[] ConvertBack(object value, Type[] targetTypes,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
+2
source

Source: https://habr.com/ru/post/1723813/


All Articles