2015-02-23 56 views
2

我有以下枚举:结合显示XAML枚举的name属性

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

我使用XAML和数据绑定,以显示我的窗口枚举:

<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中无效。

+1

你可以在你的绑定做枚举到DisplayValue的转换使用'IValueConverter'。 http://www.wpftutorial.net/ValueConverters.html – Aron 2015-02-23 10:46:14

+0

http://stackoverflow.com/questions/3985876/wpf-binding-a-listbox-to-an-enum-displaying-the-description-attribute – CarbineCoder 2015-02-23 10:50:43

+0

@CarbineCoder :我看到了这个例子。我没有得到的是如何使用它只是一个绑定到视图模型的标签。 – mosquito87 2015-02-23 13:18:59

回答

3

创建一个实现System.Windows.Data.IValueConverter接口的类并将其指定为绑定的转换器。或者,为了更方便使用,您可以创建一个实现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"/> 
+0

不知何故,这导致了空引用异常? – mosquito87 2015-02-23 13:40:48

+0

@ mosquito87这很奇怪,我想到的唯一可能性是'Convert'方法的'value'参数为null,或者由于某种原因'GetAttributeOfType'方法返回null ...您能否使用调试器来精确定位引发异常的确切行? – Grx70 2015-02-23 14:28:24

+0

好吧,就像它看起来很愚蠢,'Convert'方法试图得到一个'System.ComponentModel.DescriptionAttribute'(我盲目地遵循了你的用法例子),而枚举成员用'System.ComponentModel.DataAnnotations.DisplayAttribute ',所以难怪'GetAttributeOfType'返回null。这个问题被这两个类都具有'Description'属性的事实所掩盖......另外,我认为你的意思是获得'Name'属性。我已经相应地更新了答案。 – Grx70 2015-02-23 14:33:22