【发布时间】:2015-04-24 15:52:11
【问题描述】:
我有以下枚举:
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 没有帮助。
【问题讨论】:
-
您可以在绑定中使用
IValueConverter将Enum 转换为DisplayValue。 wpftutorial.net/ValueConverters.html -
@CarbineCoder:我看到了这个例子。我没有得到的是如何将它仅用于绑定到视图模型的标签。