我有一个转换器,允许我在SelectedItems和Generic List<MyType>
public class SelectedTiposDocsToList : BaseConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
List<MyType> MyTypeList = Selecteditems.Cast<MyType>().ToList();
return MyTypeList;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
现在这对我来说是一个常见的任务,并希望扩展这个类以允许泛型类型,这可能是这样的吗?
public class SelectedTiposDocsToList : BaseConverter, IValueConverter
{
public object Convert<T>(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
List<T> MyTypeList = Selecteditems.Cast<T>().ToList();
return MyTypeList;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
这可能吗? 如果是..如何在XAML上使用这种类型的转换器?
答案 0 :(得分:4)
不,这不是IValueConverter的有效实现。但是,您可以在参数上传递类型:
{Binding MyVariable, Converter={StaticResource SelectedTiposDocsToList}, ConverterParameter={x:Type local:MyType}}
然后您将Select
方法与Convert.ChangeType
方法一起使用:MSDN
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
var MyTypeList = Selecteditems.Cast<object>().Select((i) => System.Convert.ChangeType(i, parameter as Type)).ToList();
return MyTypeList;
}
在VS 2013上验证为编译。
答案 1 :(得分:1)
可以通过一些反思来完成:Type.MakeGenericType
获取类型,Activator.CreateInstance
调用right constructor,MethodInfo.MakeGenericMethod
将参数提供给{{ 3}}
public Type ConvertType { get; set; }
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var type = typeof(List<>).MakeGenericType(ConvertType);
var methodInfo = typeof(Enumerable).GetMethod("Cast");
var genericMethod = methodInfo.MakeGenericMethod(ConvertType);
var convertTypeList = Activator.CreateInstance(type,
genericMethod.Invoke(null, new[] { value }));
return convertTypeList;
}
您可以使用Cast
在XAML中指定类型。
<myns:SelectedTiposDocsToList x:Key="Conv" ConvertType="{x:Type myns:MyType}" />