开发者

XAML Indexer DataBinding

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 happen inside the 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 doesn't have a similar collection, So I can't afford to make seperate converte开发者_StackOverflowrs 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?


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 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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜