How can I use enum types in XAML?

davymartu picture davymartu · Jan 11, 2013 · Viewed 48.3k times · Source

I'm learning WPF and I encountered the following problem:

I have an enum type in another namespace than my XAML:

 public enum NodeType
 {
    Type_SYSTEM = 1,              // System
    Type_DB     = 2,              // Database
    Type_ROOT   = 512,            // Root folder
    Type_FOLDER = 1024,           // Folder
 }

in my XAML I'd like to trigger an image with an integer

<Image.Style>
    <Style TargetType="{x:Type Image}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Type}" Value="{NodeType: }">
                <Setter Property="Source" Value="/Images/DB.PNG"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Type}" Value="128">
                <Setter Property="Source" Value="/Images/SERVER.PNG"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Image.Style>

Is there a way to get an integer value and compare it with an enum type directly in XAML code?

My enum is in namespace AnotherNamespace.Types

<DataTrigger Binding="{Binding IntegerType}" Value="MyEnumType.Type_DB">
    <Setter Property="Source" Value="/Images/SERVER.PNG"/> 
</DataTrigger>

Answer

Rachel picture Rachel · Jan 11, 2013

I had a similar question here, and my end result was to create a generic IValueConverter that passed the enum value I wanted to match in as the ConverterParameter, and it returns true or false depending on if the bound value matches the (int) value of the Enum.

The end result looks like this:

XAML Code:

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

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;
}