【问题标题】:xaml Binding to enum. Display value instead of "ToString"xaml 绑定到枚举。显示值而不是“ToString”
【发布时间】:2016-12-13 14:10:25
【问题描述】:

我有一个枚举类型的属性。我将 wpf 控件的内容绑定到此属性。这将显示枚举值的名称。于是调用了枚举的ToString方法。

但我需要显示值,而不是字符串值。有人知道怎么做吗?

这是我的 C# 代码:

public enum Animal 
{ 
   cat = 0, 
   dog = 1, 
   mouse = 2 
}

public Animal MyAnimal { get; set; } 

void SomeMethod() { MyAnimal = dog; }  

这是在我的 XAML 中:

<Label Content="{Binding MyAnimal}">

【问题讨论】:

  • 你需要展示什么价值?
  • 为了显示枚举的 int/double/short 等值,请考虑使用值转换器并将 rhe 枚举简单地转换为其特定值。像那样 (int/double/short)EnumName.EnumStringValue.
  • 请发布您的无效代码。还可以尝试以&lt;Label Content="{Binding Visibility, RelativeSource={RelativeSource Self}}"/&gt; 为例,它表明它确实可以开箱即用。
  • public enum Animal { cat = 0, dog = 1, mouse = 2 } public Animal MyAnimal {get; set;} void SomeMethod() { MyAnimal = dog; }
  • 编辑您的问题,而不是在评论中发布代码。

标签: wpf xaml enums binding


【解决方案1】:

当您绑定到一种类型的值并希望以不同于默认 ToString() 方法提供的格式显示它时,您应该使用 DataTemplate 或 IValueConverter。由于 XAML 是一种 标记 语言,因此您不能真正将枚举值转换为标记中的 int,因此您应该使用转换器:

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        animals enumValue = (animals)value;
        return System.Convert.ToInt32(enumValue);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

<Window.Resources>
    <local:EnumConverter x:Key="conv" />
</Window.Resources>
...
<ContentControl Content="{Binding TheEnumProperty, Converter={StaticResource conv}}" />

【讨论】:

  • 嗨。谢谢mm8的回答。这行得通。但现在我还有一个问题。我必须显示数据库中的值。这个值我已经映射到一个枚举。我想用它的名字显示这个值。但是,如果我从数据库中收到一个未在枚举中定义的值,我需要显示它的值。如果我只是绑定到枚举属性,并且该属性的值超出范围,则不会显示任何内容。如果我使用转换器。始终显示该值。
  • 这肯定是与原始要求不同的要求...我不明白您如何将枚举源属性设置为枚举中不存在的数据库中的值,因为这个甚至不会编译...?
【解决方案2】:

我找到了解决办法:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (!(value is Enum)) return value;

    return Enum.IsDefined(value.GetType(), value) ? value : System.Convert.ToInt32(value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多