我可以应用我的IValueConverter转换我的枚举并在xaml端显示Display-name属性。我想知道如何在代码隐藏中做同样的事情?
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 ");
}\\
我所尝试的 - 代码背后
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,
};
请问我是否可以获得有关如何正确绑定到枚举并将集合转换为使用后面的代码使用Display-Name属性的帮助。
工作解决方案
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;