且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-18 23:23:40

如您所见,DataGrid并不在乎是否装饰了属性。您可以禁用列的自动生成并手动定义它们,或者利用AutoGeneratingColumn事件

As you can see DataGrid doesn' really care if you properties are decorated. You can either disable the autogeneration of columns and define them manually, or leverage the AutoGeneratingColumn event

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

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

You can also automate this solution by defining an attached behaviour:

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