XAML索引器数据绑定

时间:2009-11-24 19:47:35

标签: c# wpf xaml data-binding mvvm

我在名为Indexer的类中有一个X属性,假设X[Y]为我提供了另一个Z类型的对象:

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

如何在索引器中发生DataBinding?如果我做{Binding [0]},它就有效。但是{Binding X[Y]}只是将索引器参数作为字符串Y

更新 Converter是一个选项,但是我有很多带有索引器的ViewModel类,并且没有类似的集合,所以我不能为所有这些创建单独的转换器。所以我只是想知道WPF是否支持这一点,如果是,如何声明Content=X[Y] XY DataContext属性?{/ p>

1 个答案:

答案 0 :(得分:3)

我发现完成此任务的唯一方法是通过MultiBindingIMultiValueConverter

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

你的转换器:

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