[英]WPF DataGridComboBoxColumn dynamic binding of Enum
I have a datagrid to which I set item source List<User>
. 我有一个数据网格,将项目源
List<User>
设置为该网格。 One of the properties of User is Department
which is Enum with descriptions. 用户的属性之一是
Department
,它是带有说明的Enum。
In the datagrid Departments are displayed as combobox for a user to select one. 在数据网格中,部门显示为组合框,供用户选择。 I need to bind enum value and description to the
DataGridComboBoxColumn
. 我需要将枚举值和描述绑定到
DataGridComboBoxColumn
。
So far I managed either to bind Enum to DataGridComboBoxColumn.ItemsSource
thus it works but the description isn't taken into account. 到目前为止,我设法将Enum绑定到
DataGridComboBoxColumn.ItemsSource
因此它可以工作,但是没有考虑到描述。 Or set collection of Value, Description to DataGridComboBoxColumn.ItemsSource
and set DisplayMemberPath
, SelectedValuePath
. 或将“值,说明”的集合设置为
DataGridComboBoxColumn.ItemsSource
并设置DisplayMemberPath
, SelectedValuePath
。 But in this case the value doesn't bind to DataGridComboBoxColumn. 但是在这种情况下,该值不会绑定到DataGridComboBoxColumn。
The View: 风景:
<DataGrid x:Name="userData" HorizontalAlignment="Stretch" Margin="10,157,10,80" VerticalAlignment="Stretch" Height="Auto" Width="Auto"
AutoGeneratingColumn="UserData_OnAutoGeneratingColumn" DisplayMemberPath="Description"/>
The Code: 编码:
private void UserData_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column.SortMemberPath == "Department")
{
(e.Column as DataGridComboBoxColumn).ItemsSource = EnumExtension.ProvideValue();
(e.Column as DataGridComboBoxColumn).DisplayMemberPath = "Description";
(e.Column as DataGridComboBoxColumn).SelectedValueBinding = new Binding("Value");
(e.Column as DataGridComboBoxColumn).SelectedValuePath = "Value";
}
}
Enum extension: 枚举扩展名:
public static class EnumExtension
{
public static List<ValueDescriptionVm<Departments>> ProvideValue()
{
return Enum.GetValues(typeof(Departments))
.Cast<object>()
.Select(enumValue => new ValueDescriptionVm<Departments>()
{
Value = (Departments)enumValue,
Description = GetDescription((Enum)enumValue)
}).ToList();
}
private static string GetDescription(Enum enumValue)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return enumValue.ToString();
}
}
The path of the SelectedValueBinding
should be the name of the property of the User
class: SelectedValueBinding
的路径应为User
类的属性的名称:
(e.Column as DataGridComboBoxColumn).SelectedValueBinding = new Binding("Department");
Then the binding should work provided that the type of the Department
property of the User
class and the Value
property of the ValueDescriptionVm<Departments>
class is the same. 然后,只要
User
类的Department
属性的类型和ValueDescriptionVm<Departments>
类的Value
属性的类型相同,绑定就应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.