Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用来自XAML的通用IValueConverter_C#_Wpf_Xaml - Fatal编程技术网

C# 使用来自XAML的通用IValueConverter

C# 使用来自XAML的通用IValueConverter,c#,wpf,xaml,C#,Wpf,Xaml,我有一个实现IValueConverter的泛型类。比如: class MyValueConverter<T> : IValueConverter public class MyMarkupExtension : MarkupExtension { public MyMarkupExtension() { this.Type = /* some default type */; } public MyMarkupExtension(Typ

我有一个实现
IValueConverter
的泛型类。比如:

class MyValueConverter<T> : IValueConverter
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);
    }
}
类MyValueConverter:IValueConverter
有了XAML 2009,我可以这样使用它:

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

但显然,“编译”XAML不允许这样做(我想我们必须等待.NET5)

我当前的解决方法是针对每种用法对其进行子类化:

class FooMyValueConverter : MyValueConverter<Foo>
类FooMyValueConverter:MyValueConverter

是否可以仅使用XAML 2006在标记中执行此操作?

您可能可以使用自定义()来执行此操作。比如:

class MyValueConverter<T> : IValueConverter
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);
    }
}
公共类MyMarkupExtension:MarkupExtension{
公共MyMarkupExtension(){
this.Type=/*某些默认类型*/;
}
公共MyMarkupExtension(类型){
this.Type=Type;
}
公共类型类型{get;private set;}
公共覆盖对象ProviderValue(IServiceProvider服务提供程序){
Type Type=typeof(MyValueConverter).MakeGenericType(this.Type);
返回Activator.CreateInstance(类型);
}
}

然后您可以像
{Binding…Converter={local:MyMarkup{x:Type BounceEase}}}

一样使用它,这是个好主意。我只是将其设置为泛型,这样我就可以实例化任何泛型类型。您是否碰巧在那里遇到了错误MC6022?(试图找出我是否有同样的问题,或者我是否应该创建一个新问题。)@o.r.mapper,这是4年前2个技术堆栈;我真的不记得了。