Search code examples
wpfwpfdatagrid

Columns in DataGrid are not generated if the itemssource contains 0 rows to display


I am assigning a datatable with multiple columns and zero rows to WPF data-grid. I am using auto-generated columns. As there are no rows to display the AutoGeneratingColumn event is not at all triggered. Because of the that it renders Data-grid in a weird manner: one single template row and now columns.

Is there any workaround for this problem? Please guide.

Regards, Priyank


Solution

  • This is actually by design. The data grid uses reflection internally to infer the columns from the data type that is available in the ItemSource collection. When there are no items it is not possible for the data grid to display the column headers correctly.

    There are two possible solution to this:

    1. Bind your grid to a static resource. This way the grid will know the clr type to which it will be bound and will correctly generate the columns.
    2. Do not rely on AutoGeneratedColumns ;)