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?
Use the Enum. ToObject() method to convert integers to enum members, as shown below.
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.
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.
On a technical level, there's nothing wrong with using an enum as the type used in a generic type.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With