如何在 XAML 中使用枚举类型? [英] How can I use enum types in XAML?

查看:43
本文介绍了如何在 XAML 中使用枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习WPF,遇到了以下问题:

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

我在另一个命名空间中有一个枚举类型而不是我的 XAML:

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
 }

在我的 XAML 中,我想用整数触发图像

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>

有没有办法直接在 XAML 代码中获取整数值并将其与枚举类型进行比较?

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

我的枚举位于命名空间 AnotherNamespace.Types

My enum is in namespace AnotherNamespace.Types

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

推荐答案

我在这里有一个类似的问题,我的最终结果是创建了一个通用的 IValueConverter传递了我想要匹配的 enum 值作为 ConverterParameter,它返回 truefalse 取决于是否绑定值与枚举的 (int) 值匹配.

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.

最终结果如下:

XAML 代码:

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

转换器

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

这篇关于如何在 XAML 中使用枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆