I have the following enum:
public enum ViewMode
{
[Display(Name = "Neu")]
New,
[Display(Name = "Bearbeiten")]
Edit,
[Display(Name = "Suchen")]
Search
}
I'm using xaml and databinding to show the enum in my window:
<Label Content="{Binding CurrentViewModel.ViewMode}" Grid.Column="2" VerticalContentAlignment="Bottom" Height="43" HorizontalContentAlignment="Right"/>
But this doesn't show the display name attribute. How can I do so?
In my viewModel I can get the display name attribute by using an extension method:
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;
}
}
Usage is string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;
.
However, this doesn't help in XAML.