我在一个名为 X
的类中有一个 Indexer
属性,假设 X[Y]
给我另一个类型为 Z
:
<ContentControl Content="{Binding X[Y]}" ...???
如何在索引器中创建一个DataBinding
?如果我执行 {Binding [0]}
,它会起作用。但是 {Binding X[Y]}
只是将索引器参数作为 Y
的字符串。
更新:
Converter
是一个选项,但我有很多带有索引器的 ViewModel 类,但没有类似的集合,所以我负担不起为所有这些创建单独的转换器。所以我只想知道 WPF 是否支持此功能,如何声明 Content=X[Y]
其中 X
和 Y
是 DataContext
属性?
最佳答案
我发现实现此目的的唯一方法是通过 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();
}
}
关于c# - XAML 索引器数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1792478/