WPF DataGridComboBoxColumn动态绑定Enum

时间:2017-08-14 22:59:42

标签: c# wpf data-binding wpfdatagrid datagridcomboboxcolumn

我有一个数据网格,我设置了项目源List<User>。 User的一个属性是Department,它是带有描述的Enum。

在数据网格中,部门显示为组合框,供用户选择。 我需要将枚举值和描述绑定到DataGridComboBoxColumn

到目前为止,我设法将Enum绑定到DataGridComboBoxColumn.ItemsSource,因此它可以正常工作,但描述并未考虑在内。 或者将值集,描述集合设置为DataGridComboBoxColumn.ItemsSource并设置DisplayMemberPathSelectedValuePath。但在这种情况下,该值不会绑定到DataGridComboBoxColumn。

观点:

 <DataGrid x:Name="userData" HorizontalAlignment="Stretch" Margin="10,157,10,80" VerticalAlignment="Stretch" Height="Auto" Width="Auto"
 AutoGeneratingColumn="UserData_OnAutoGeneratingColumn" DisplayMemberPath="Description"/>

守则:

    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";
        }
    }

枚举扩展名:

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();
    }
}

1 个答案:

答案 0 :(得分:1)

SelectedValueBinding的路径应该是User类的属性名称:

(e.Column as DataGridComboBoxColumn).SelectedValueBinding = new Binding("Department");

如果Department类的User属性的类型和Value类的ValueDescriptionVm<Departments>属性相同,则绑定应该有效。