我有一个转换器,允许我在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();
}
}
Run Code Online (Sandbox Code Playgroud)
现在这对我来说是一个常见的任务,并希望扩展这个类以允许泛型类型,这可能是这样的吗?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这可能吗 ?如果是..如何在XAML上使用这种类型的转换器?
这可以通过一些反射来完成:Type.MakeGenericType获取类型,Activator.CreateInstance调用正确的构造函数,并将MethodInfo.MakeGenericMethod参数提供给Cast。
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用x:Type 在 XAML 中指定类型。
<myns:SelectedTiposDocsToList x:Key="Conv" ConvertType="{x:Type myns:MyType}" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1505 次 |
| 最近记录: |