我有以下枚举:结合显示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中无效。
你可以在你的绑定做枚举到DisplayValue的转换使用'IValueConverter'。 http://www.wpftutorial.net/ValueConverters.html – Aron 2015-02-23 10:46:14
http://stackoverflow.com/questions/3985876/wpf-binding-a-listbox-to-an-enum-displaying-the-description-attribute – CarbineCoder 2015-02-23 10:50:43
@CarbineCoder :我看到了这个例子。我没有得到的是如何使用它只是一个绑定到视图模型的标签。 – mosquito87 2015-02-23 13:18:59