Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a generic Int-to-Enum Converter?

I'd like to be able to say

<DataTrigger Binding="{Binding SomeIntValue}" 
             Value="{x:Static local:MyEnum.SomeValue}">

and to have it resolve as True if the int value is equal to (int)MyEnum.Value

I know I could make a Converter that returns (MyEnum)intValue, however then I'd have to make a converter for every Enum type I use in my DataTriggers.

Is there a generic way to create a converter that would give me this kind of functionality?

like image 325
Rachel Avatar asked Aug 18 '11 16:08

Rachel


People also ask

How do I convert an int to enum?

Use the Enum. ToObject() method to convert integers to enum members, as shown below.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Is enum generic?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation.

Can enum be generic C#?

On a technical level, there's nothing wrong with using an enum as the type used in a generic type.


1 Answers

You could also go the other way around and convert the enum to int for the Value using a custom Markup Extension.

Example

<DataTrigger Binding="{Binding Path=MyNumber}"
             Value="{Markup:EnumToInt {x:Static Visibility.Visible}}">

EnumToIntExtension

public class EnumToIntExtension : MarkupExtension
{
    public object EnumValue
    {
        get;
        set;
    }
    public EnumToIntExtension(object enumValue)
    {
        this.EnumValue = enumValue;
    } 
    public override object ProvideValue(IServiceProvider provider)
    {
        if (EnumValue != null && EnumValue is Enum)
        {
            return System.Convert.ToInt32(EnumValue);
        }
        return -1;
    }
}
like image 191
Fredrik Hedblad Avatar answered Sep 21 '22 03:09

Fredrik Hedblad