Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Generic Converter for

Tags:

c#

generics

wpf

I have a converter that allow me to convert between SelectedItems and a 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();
    }
} 

Now this is a common task for me and want to extend this class to allow a generic type is this something like this maybe ?

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();
    }
} 

Is this Possible ? If Yes.. How to use thsi type of converter on XAML ?

like image 616
Juan Pablo Gomez Avatar asked May 20 '14 00:05

Juan Pablo Gomez


1 Answers

No, this would not be a valid implementation of IValueConverter. However, you can pass a type on the parameter:

{Binding MyVariable, Converter={StaticResource SelectedTiposDocsToList}, ConverterParameter={x:Type local:MyType}}

Then you would use Select with the Convert.ChangeType method: 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;
}

Verified as compiling on VS 2013.

like image 67
BradleyDotNET Avatar answered Sep 30 '22 00:09

BradleyDotNET