2009-11-24 89 views
3

我有一个名为X类的Indexer属性,假设X[Y]给我Z类型的另一个对象:XAML索引数据绑定

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

我怎样才能让一个DataBinding发生索引里面?它适用于我{Binding [0]}。但{Binding X[Y]}只是将索引器参数作为字符串,即Y

更新: Converter是一种选择,但我有很多视图模型类与索引,并没有类似的收藏,所以我不能做所有这些单独的转换器。所以我只是想知道这是在WPF支持如果是的话,如何声明Content=X[Y]其中XYDataContext属性?

回答

2

我发现完成这个的唯一方法是通过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(); 
    } 
} 
+0

好的,谢谢,这是显而易见的解决方案,如果只有一个班。但是我有很多ViewModel类与此类似,所以我不能承担单独的转换器,而是将索引器逻辑更改为其他。 – 2009-11-24 21:16:00

+0

我已经完成并更新了这个功能,以适应多种类型的集合。 – user7116 2011-08-30 19:41:34