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?
We've wanted to do this a few times in the past as well, so we built several extension methods (on int, long, etc) to help us out. The core of all of these is implemented in a single static generic TryAsEnum method:
This implementation handles Enums with any underlying type, as well as enums defined with the [Flags] attribute.
It is possible to create a converter between enum values and their underlying integral types in a reusable way -- that is, you don't need to define a new converter for each enum types. There's enough information provided to
Convert
andConvertBack
for this.When invoked, this converter flips the value's type between int/enum value based purely on the
value
andtargetType
values. There are no hard-coded enum types.You could do a ToString() on the int value and then pass that into the static Enum.Parse or Enum.TryParse method which takes the enum type you care about and returns the appropriate value.
This isn't a perfect solution though because it won't work with integers that represent the binary ORing of multiple enum values
I think I figured it out
I just needed to set my
ConverterParameter
instead of theValue
equal to the Enum I am looking for, and evaluate for True/FalseConverter
You could also go the other way around and convert the enum to int for the Value using a custom Markup Extension.
Example
EnumToIntExtension