c#通用转换器

时间:2014-05-20 00:02:58

标签: c# wpf generics

我有一个转换器,允许我在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上使用这种类型的转换器?

2 个答案:

答案 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 constructorMethodInfo.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}" />