Search code examples
c#wpfdatagrid

Can I set DataGridHeader by AutoGeneratedColumns?


I want set header FirstName,LastName by AutoGeneratedColumns. I tried this code, but DataGrid Header display Name1,Name2.

I know, DataGridColumns can make header. but I want set header by AutoGeneratedColumns.

Is there anything way?

Thank you for taking the time review for this!

ViewModel

public class DataGridItems
{
    [Description("FirstName")]
    public string Name1 { get; set; }

    [Description("LastName")]
    public string Name2 { get; set; }
}

MainWindow

public partial class MainWindow : Window
{
    public List<DataGridItems> ItemsSource { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = Enumerable.Range(1, 10).Select(a => new DataGridItems { Name1 = a.ToString(), Name2 = "Last" + a.ToString() });
    }
}

XAML

<Grid>
    <DataGrid ItemsSource="{Binding}"/>
</Grid>

Solution

  • You could handle the AutoGeneratingColumn event in the view:

    public partial class MainWindow : Window
    {
        public List<DataGridItems> ItemsSource { get; set; }
    
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = Enumerable.Range(1, 10).Select(a => new DataGridItems { Name1 = a.ToString(), Name2 = "Last" + a.ToString() });
        }
    
    
        private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            DescriptionAttribute descriptionAttribute = typeof(DataGridItems)
                .GetProperty(e.PropertyName)?
                .GetCustomAttributes(true)?
                .OfType<DescriptionAttribute>()
                .FirstOrDefault();
            if (descriptionAttribute != null)
                e.Column.Header = descriptionAttribute.Description;
        }
    }
    

    XAML:

    <DataGrid ItemsSource="{Binding}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>
    

    It's is not the responsibility of the view model to provide functionality to set the headers of a DataGrid in the view. This should be implemented in the view or the control, much like when you set the headers to some fixed values in the XAML markup.