在WPF DataGrid中显示“显示名称”而不是字段名称

时间:2014-01-16 14:10:31

标签: c# wpf xaml datagrid

这是我的班级定义。

    public class Customer
    {
        [Display(Name="Customer ID")]
        public int ID { get; set; }
        [Display(Name="Customer Name")]
        public string CusName { get; set; }
    }

这是我的XAML代码

<DataGrid Name="DataGrid" />

这是数据绑定

    public Test()
    {
        InitializeComponent();


        List<Customer> cus = new List<Customer>();
        cus.Add(new Customer() { ID = 1, CusName = "Jackson" });
        cus.Add(new Customer() { ID = 2, CusName = "Micheal" });
        cus.Add(new Customer() { ID = 3, CusName = "Jackson" });
        DataGrid.ItemsSource = cus;
    }

结果如下:

DataGrid Result

DataGrid标题列显示ID,CusName,它们是客户的字段名称。

如何使DataGrid标题列显示客户ID,客户名称而不是ID,CusNumber?它们位于[显示]属性

1 个答案:

答案 0 :(得分:1)

正如您所看到的,DataGrid并不关心您是否修饰了属性。您可以禁用列的自动生成并手动定义它们,也可以利用AutoGeneratingColumn事件

<DataGrid x:Name="grid" AutoGeneratingColumn="grid_AutoGeneratingColumn"/>


private void grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "ID":
                e.Column.Header = "Customer ID";
                break;

            case "CusName":
                e.Column.Header = "Customer Name";
                break;

            default:
                break;
        }
    }

您还可以通过定义附加行为来自动执行此解决方案:

public static class CustomColumnHeadersProperty
{
    public static DependencyProperty ItemTypeProperty = DependencyProperty.RegisterAttached(
        "ItemType",
        typeof(Type),
        typeof(CustomColumnHeadersProperty),
        new PropertyMetadata(OnItemTypeChanged));

    public static void SetItemType(DependencyObject obj, Type value)
    {
        obj.SetValue(ItemTypeProperty, value);
    }

    public static Type GetItemType(DependencyObject obj)
    {
        return (Type)obj.GetValue(ItemTypeProperty);
    }

    private static void OnItemTypeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        var dataGrid = sender as DataGrid;

        if (args.NewValue != null)
            dataGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;
        else
            dataGrid.AutoGeneratingColumn -= dataGrid_AutoGeneratingColumn;
    }

    static void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var type = GetItemType(sender as DataGrid);

        var displayAttribute = type.GetProperty(e.PropertyName).GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
        if (displayAttribute != null)
            e.Column.Header = displayAttribute.Name;
    }
}


<DataGrid x:Name="grid" local:CustomColumnHeadersProperty.ItemType="{x:Type local:MyClass}"/>