WPF - Changing a Column Name on a Bound DataGrid

I mainly use the ItemSource property for a datagrid to bind a shared list to my datagrid. However, I would really like to change the headers, I tried the following, but I get an exception at runtime:

dgtest.Columns[1].Header = "edited";
+3
source share
3 answers

You can change it to an event ItemDataBound:

public void yourDataGrid_OnItemDataBound(object s, DataGridItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        // Change the cell index to the column index you want... I just used 0
        e.Item.Cells[0].Text = "Text you want in header.";
    }
}

If the grid is already connected, you should be able to:

yourDataGrid.Columns[0].Header = "Text you want in header.";

You are probably getting an error because you are trying to change the text before binding it.

+3
source

I used the AutoGeneratingColumn event and attribute to set the column names.

First create an attribute class ...

    public class ColumnNameAttribute : System.Attribute
    {
        public ColumnNameAttribute(string Name) { this.Name = Name; }
        public string Name { get; set; }
    }

Then I decorate my data class members with a new attribute ...

    public class Test
    {
        [ColumnName("User Name")]
        public string Name { get; set; }
        [ColumnName("User Id")]
        public string UserID { get; set; }
    }

AutoGeneratingColumn...

    void dgPrimaryGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var desc = e.PropertyDescriptor as PropertyDescriptor;
        var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
        if(att != null)
        {
            e.Column.Header = att.Name;
        }
    }

... ...

        dgPrimaryGrid.AutoGeneratingColumn += dgPrimaryGrid_AutoGeneratingColumn;

        var data = new object[] 
        {
            new Test() { Name = "Joe", UserID = "1" }
        };
        dgPrimaryGrid.ItemsSource = data;

. , ( ).

A DataGrid with Columns Renamed

, , , . , , .

+10

AutoGeneratedColumns event in wpf for change column name

datagrid1.AutoGeneratedColumns += datagrid1_AutoGeneratedColumns;

void datagrid1_AutoGeneratedColumns(object sender, EventArgs e)
{
    datagrid1.Columns[0].Header = "New Column Name";
}
+3
source

Source: https://habr.com/ru/post/1758964/


All Articles