How do you rename DataGrid columns when AutoGenerateColumns = True?

jmulmer picture jmulmer · Nov 27, 2012 · Viewed 16.4k times · Source

I have a simple data structure class:

public class Client {
    public String name {set; get;}
    public String claim_number {set; get;}
}

Which I am feeding into a DataGrid:

this.data_grid_clients.ItemSource = this.clients;

I would like to change the column headings. Ie: claim_number to "Claim Number". I know this can be done when you manually create the columns by doing something like:

this.data_grid_clients.Columns[0].Header = "Claim Number"

However, the Columns property is empty when auto-generating the columns. Is there a way to rename the columns, or do I have to manually generate the columns?

Answer

Ekk picture Ekk · Nov 27, 2012

You can use DisplayNameAttribute and update some part of your code to achieve what you want.

The first thing you have to do is, adding a [DisplayName("")] to properties in the Client class.

public class Client {
    [DisplayName("Column Name 1")]
    public String name {set; get;}

    [DisplayName("Clain Number")]
    public String claim_number {set; get;}
}

The update you xaml code, add an event handler to AutoGenerationColumn event.

<dg:DataGrid AutoGenerateColumns="True" AutoGeneratingColumn="OnAutoGeneratingColumn">
</dg:DataGrid>

Finally, add a method to the code-behind.

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    var displayName = GetPropertyDisplayName(e.PropertyDescriptor);

    if (!string.IsNullOrEmpty(displayName))
    {
        e.Column.Header = displayName;
    }

}

public static string GetPropertyDisplayName(object descriptor)
{
    var pd = descriptor as PropertyDescriptor;

    if (pd != null)
    {
        // Check for DisplayName attribute and set the column header accordingly
        var displayName = pd.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;

        if (displayName != null && displayName != DisplayNameAttribute.Default)
        {
            return displayName.DisplayName;
        }

    }
    else
    {
        var pi = descriptor as PropertyInfo;

        if (pi != null)
        {
            // Check for DisplayName attribute and set the column header accordingly
            Object[] attributes = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true);
            for (int i = 0; i < attributes.Length; ++i)
            {
                var displayName = attributes[i] as DisplayNameAttribute;
                if (displayName != null && displayName != DisplayNameAttribute.Default)
                {
                    return displayName.DisplayName;
                }
            }
        }
    }

    return null;
}