动态枚举器 [英] Dynamic enum converter

查看:150
本文介绍了动态枚举器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个动态的双向转换器在我的应用程序的所有可能的枚举。



我不希望有创建每个转换器枚举,我想创建一个转换器,它提供了从枚举转换为字节和字节反之亦然枚举。



我怎样才能到达那里?我的做法已经是2路,但需要在代码的静态投(MyEnum)



 公共类MyEnumConverter:的MarkupExtension,的IValueConverter 
{
公共对象转换(对象的值,System.Type的TARGETTYPE,对象参数,CultureInfo的文化){
回报(MyEnum)值;
}

公共对象ConvertBack(对象的值,System.Type的TARGETTYPE,对象参数,CultureInfo的文化){
回报(字节)值;
}

公众覆盖对象ProvideValue(System.IServiceProvider的ServiceProvider){
返回这一点;
}
}


解决方案

我。相信你能做到这两种不同的方式。



选项1:采取对转换方法利用了 TARGETTYPE 参数。当你需要转换为枚举,那么 TARGETTYPE 是枚举类型。您可以使用对静态方法之一 System.Enum 类做转换



选项2:在XAML中,使用ConverterParameter你要转换为枚举类型来传递:

 转换器= {地方:MyConverter, ConverterParameter = {X:类型MyEnumType}} 

如果你走这条路线,那么该类型将在的转换方法参数参数。再次,在 System.Enum 类将做繁重你。


的静态方法

I want to create a dynamic 2-way-converter for all possible enums in my application.

I don't want to have to create a converter for each enum, I want to create one converter that provides converting from enum to byte and from byte to enum vice versa.

How can I get there? My approach is already 2-way but requires a static cast (MyEnum) in the code:

public class MyEnumConverter : MarkupExtension, IValueConverter 
        {
        public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) {
            return (MyEnum)value;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) {
            return (byte)value;
        }

        public override object ProvideValue(System.IServiceProvider serviceProvider) {
            return this;
        }
    }

解决方案

I believe you can do this 2 different ways.

Option 1: Take advantage of the targetType parameter on the convert methods. When you need to convert to the enum, then targetType is the enum type. You can use one of the static methods on the System.Enum class to do the conversion.

Option 2: In your xaml, use the ConverterParameter to pass in the enum type you want to convert to:

Converter={local:MyConverter, ConverterParameter={x:Type MyEnumType}}

If you go that route, then the type will be in the parameter parameter of the convert methods. Again, the static methods on the System.Enum class will do the heavy lifting for you.

这篇关于动态枚举器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆