C# XAML索引器数据绑定
我在一个名为C# XAML索引器数据绑定,c#,wpf,xaml,data-binding,mvvm,C#,Wpf,Xaml,Data Binding,Mvvm,我在一个名为X的类中得到了一个Indexer属性,假设X[Y]给了我另一个Z类型的对象: <ContentControl Content="{Binding X[Y]}" ...??? 我发现实现这一点的唯一方法是通过a和a 和您的转换器: public class SelectEmployeeConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType,
X
的类中得到了一个Indexer
属性,假设X[Y]
给了我另一个Z
类型的对象:
<ContentControl Content="{Binding X[Y]}" ...???
我发现实现这一点的唯一方法是通过a和a
和您的转换器:
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();
}
}
public类选择EmployeeConverter:IMultiValueConverter
{
公共对象转换(对象[]值,类型targetType,
对象参数,CultureInfo(区域性)
{
Assert(values.Length>=2);
//改变这种假设
变量数组=值[0]作为数组;
var list=值[0]为IList;
var enumerable=作为IEnumerable的值[0];
var指数=转换为32(值[1]);
//并检查边界
如果(数组!=null&&index>=0&&index=0&&index=0)
{
int ii=0;
foreach(可枚举中的变量项)
{
如果(ii++==索引)返回项;
}
}
不做任何事;
}
公共对象[]转换回(对象值,类型[]targetTypes,
对象参数,CultureInfo(区域性)
{
抛出新的NotImplementedException();
}
}
是的,谢谢,如果只有一个类,这是显而易见的解决方案。但是我有很多类似的ViewModel类,所以我负担不起单独的转换器,相反,我将索引器逻辑更改为其他类型。我已经继续并更新了它,以跨多种集合类型工作。
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();
}
}