I am able to apply my IValueConverter which converters my enum and shows the Display-name Attribute on the xaml side. I'm wondering how would I do the same in code-behind?
EnumToDisplayAttribConverter.cs
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!value.GetType().IsEnum)
{
throw new ArgumentException("Value must be an Enumeration type");
}
var fieldInfo = value.GetType().GetField(value.ToString());
var array = fieldInfo.GetCustomAttributes(false);
foreach (var attrib in array)
{
if (attrib is DisplayAttribute)
{
DisplayAttribute displayAttrib = attrib as DisplayAttribute;
//if there is no resource assume we don't care about lization
if (displayAttrib.ResourceType == null)
return displayAttrib.Name;
// per http://stackoverflow.com/questions/5015830/get-the-value-of-displayname-attribute
ResourceManager resourceManager = new ResourceManager(displayAttrib.ResourceType.FullName, displayAttrib.ResourceType.Assembly);
var entry =
resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttrib.Name);
var key = entry.Value.ToString();
return key;
}
}
//if we get here than there was no attrib, just pretty up the output by spacing on case
// per http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array
string name = Enum.GetName(value.GetType(), value);
return Regex.Replace(name, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ");
}\\
What I've Tried - Code Behind
var converter = new EnumToDisplayAttribConverter();
var converted =
(IEnumerable<ReportArguements.NoteOptions>)
converter.Convert(
Enum.GetValues(typeof(ReportArguements.NoteOptions))
.Cast<ReportArguements.NoteOptions>(), typeof(IEnumerable<ReportArguements.NoteOptions>), null, null);
var notesOption = new ComboBox
{
ItemsSource = converted,
SelectedIndex = 0,
};
May I ask if I can get assistance on how to properly bind to an enum and converting the collection to use Display-Name attribute using code behind.
Working solution
var datatemplate = new DataTemplate();
Binding binding = new Binding();
binding.Converter = new EnumToDisplayAttribConverter();
FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);
datatemplate.VisualTree = textElement;
var notesOption = new ComboBox
{
SelectedIndex = 0,
};
notesOption.ItemTemplate = datatemplate;
notesOption.ItemsSource = Enum.GetValues(typeof(ReportArguements.NoteOptions)).Cast<ReportArguements.NoteOptions>();
return notesOption;