我在名为Indexer
的类中有一个X
属性,假设X[Y]
为我提供了另一个Z
类型的对象:
<ContentControl Content="{Binding X[Y]}" ...???
如何在索引器中发生DataBinding
?如果我做{Binding [0]}
,它就有效。但是{Binding X[Y]}
只是将索引器参数作为字符串Y
。
更新
Converter
是一个选项,但是我有很多带有索引器的ViewModel类,并且没有类似的集合,所以我不能为所有这些创建单独的转换器。所以我只是想知道WPF是否支持这一点,如果是,如何声明Content=X[Y]
X
和Y
DataContext
属性?{/ p>
答案 0 :(得分:3)
我发现完成此任务的唯一方法是通过MultiBinding和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>
你的转换器:
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();
}
}