Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c# - How can I use enum types in XAML?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...