c# - 绑定(bind)到 xaml 中枚举的显示名称属性

标签 c# wpf xaml enums

我有以下枚举:

public enum ViewMode
{
    [Display(Name = "Neu")]
    New,
    [Display(Name = "Bearbeiten")]
    Edit,
    [Display(Name = "Suchen")]
    Search
}

我正在使用 xaml 和数据绑定(bind)在我的窗口中显示枚举:
<Label Content="{Binding CurrentViewModel.ViewMode}" Grid.Column="2" VerticalContentAlignment="Bottom" Height="43" HorizontalContentAlignment="Right"/>

但这不显示显示名称属性。我该怎么做?

在我的 viewModel 中,我可以使用扩展方法获取显示名称属性:
public static class EnumHelper
{
    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="enumVal">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute
    {
        var type = enumVal.GetType();
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
        return (attributes.Length > 0) ? (T)attributes[0] : null;
    }
}

用法是 string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description; .
但是,这对 XAML 没有帮助。

最佳答案

创建一个实现 System.Windows.Data.IValueConverter 的类接口(interface)并将其指定为绑定(bind)的转换器。可选地,为了更方便使用,您可以创建一个实现 System.Windows.Markup.MarkupExtension 的“提供者”类。 (实际上你可以只用一个类)。您的最终结果可能类似于此示例:

public class MyConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((Enum)value).GetAttributeOfType<DisplayAttribute>().Name;
    }

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

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

然后在 XAML 中:
<Label Content="{Binding CurrentViewModel.ViewMode, Converter={local:MyConverter}}" Grid.Column="2" VerticalContentAlignment="Bottom" Height="43" HorizontalContentAlignment="Right"/>

关于c# - 绑定(bind)到 xaml 中枚举的显示名称属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28671828/

相关文章:

wpf - WPF 中包含下标和内嵌图像的文本的本地化

wpf - 我可以向样式添加资源或 ResourceDictionary 吗?

c# - Windows Phone 8 列表框

c# - DotNetZip 保存到流

c# - 我可以从 InvalidConstraintException 中检索受影响的约束吗?

wpf - MVVM问题, View 中的事件触发

c# - 在 WPF 上使用 MVVM 模式时,TextBox.LineCount 和 TextBox.GetLastVisibleLineIndex() 始终为 -1

wpf - 签名时发生错误

c# - 将 JSON 和输入文件传回 Controller MVC 4

c# - 如何将字符串 "dd.MM.yyyy HH:mm:ss.mmm"转换为 C# 中的日期时间