Search code examples
c#wpfenumsconvertersdatatrigger

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?


Solution

  • I think I figured it out

    I just needed to set my ConverterParameter instead of the Value equal to the Enum I am looking for, and evaluate for True/False

    <DataTrigger Value="True"
                 Binding="{Binding SomeIntValue, 
                     Converter={StaticResource IsIntEqualEnumConverter},
                     ConverterParameter={x:Static local:MyEnum.SomeValue}}">
    

    Converter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter == null || value == null) return false;
    
        if (parameter.GetType().IsEnum && value is int)
        {
            return (int)parameter == (int)value;
        } 
        return false;
    }