Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Generic IValueConverter from XAML

Tags:

c#

wpf

xaml

I have a generic class implementing IValueConverter. Something like:

class MyValueConverter<T> : IValueConverter

With XAML 2009, I can use it like this:

<my:MyValueConverter x:TypeArguments='x:String'/>

But apparently that's not allowed for "compiled" XAML (I guess we'll have to wait for .NET 5)

My current workaround is subclassing it for each usage:

class FooMyValueConverter : MyValueConverter<Foo>

Is it possible to do this in markup only using XAML 2006?

like image 944
Diego Mijelshon Avatar asked Apr 29 '11 14:04

Diego Mijelshon


1 Answers

You could probably do this with a custom MarkupExtension(archive)(v4). Something like:

public class MyMarkupExtension : MarkupExtension {

    public MyMarkupExtension() {
        this.Type = /* some default type */;
    }

    public MyMarkupExtension(Type type) {
        this.Type = type;
    }

    public Type Type { get; private set; }

    public override object ProvideValue(IServiceProvider serviceProvider) {
        Type type = typeof(MyValueConverter<>).MakeGenericType(this.Type);
        return Activator.CreateInstance(type);
    }
}

Then you'd use it like {Binding ... Converter={local:MyMarkup {x:Type BounceEase}}}

like image 119
CodeNaked Avatar answered Oct 21 '22 01:10

CodeNaked