DataGrid 具有 AutoGeneratedColumns = true。一些属性是枚举,因此对应的列是 DatagridComboBoxColumn。枚举定义具有如下描述属性:
public enum MyEnum
{
[Description("first")]
FirstEnum,
[Description("second")]
SecondEnum
}
我已经有一个实用方法可以在 ComboBox 中显示 Description 属性:
public class EnumToItemsSource : MarkupExtension
{
private readonly Type _type;
public EnumToItemsSource(Type type)
{
_type = type;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Enum.GetValues(_type).Cast<object>().Select(e => new { Value = e,
Description = GetEnumDescription((Enum)e) });
}
public static string GetEnumDescription(Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attributes = fieldInfo.GetCustomAttributes(false);
if (attributes.Length == 0)
return enumObj.ToString();
else
{
DescriptionAttribute attrib = attributes.OfType<DescriptionAttribute>().FirstOrDefault();
if (attrib != null)
return attrib.Description;
else
return "No description";
}
}
}
我在 xaml 中使用它如下:
<ComboBox ItemsSource="{utils:EnumToItemsSource {x:Type myenums:MyEnum}}"
DisplayMemberPath="Description"
SelectedValuePath="Value"
SelectedValue="{Binding SomeProperty}"/>
现在我的问题是,如何将其应用于自动生成的列?
编辑第一次尝试
我在 AutoGeneratingColumn 事件处理程序中尝试了第一个解决方案:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridComboBoxColumn col = e.Column as DataGridComboBoxColumn;
if (col != null)
{
col.ItemsSource = EnumToIEnumerable.GetIEnumerable(e.PropertyType);
col.DisplayMemberPath = "Value";
col.SelectedValuePath = "Key";
col.SelectedValueBinding = new Binding(e.PropertyName);
}
}
为此,我必须编写一个新的辅助静态方法来为组合框项目源提供列表:
public static class EnumToIEnumerable
{
public static IEnumerable<KeyValuePair<Enum, string>> GetIEnumrable(Type type)
{
return Enum.GetValues(type).Cast<Enum>().Select((e) => new KeyValuePair<Enum, string>(e,
EnumDescriptionConverter.GetEnumDescription((Enum)e)));
}
}
它用于显示描述。但程序无法将 SelectedValue 转换为绑定属性。它抛出静默异常,并且组合框是红线。
我尝试用英文翻译错误消息:
Conversion of EnumConverter is not possible from System.Collections.Generic.KeyValuePair
System.Windows.Data Error: 7 : ConvertBack cannot convert value '[Surface, m²]' (type 'KeyValuePair`2'). BindingExpression:Path=TypeQuantite; DataItem='MscaGridLineViewModel' (HashCode=39414053); target element is 'TextBlockComboBox' (Name=''); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: Conversion de EnumConverter impossible à partir de System.Collections.Generic.KeyValuePair`2[[System.Enum, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].
我不明白为什么它写的目标属性是'SelectedItem',因为SelectedValuePath 包含一个枚举对象,而SelectedValueBinding 将它绑定到一个枚举类型的“MyEnum”类型的属性。