Generic WPF DataGrid MVVM

171 views Asked by At

Is it possible in WPF to have a Datagrid with some common functionality for different itemsources? Can we have a Datagrid in a control which can accept any observable collection. is there a way we can pass the Column information or define column template to show only certain columns with their header and bindings passed to the control containing the Datagrid? Rest of the functionalities like add. delete, sort, clicks will be using Commnds and will be common for all itemSources. The only thing hindering is the way I can define columns for this Datagrid? If it is possible to pass the Datagrid.Columns to the control as template or any other way.

2

There are 2 answers

1
Julius On BEST ANSWER

You will need to handle the DataGrid.AutoGeneratingColumn event, then set the column's Visibility property according to your needs: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.datagrid.autogeneratingcolumn?view=net-5.0

0
EldHasp On

You write data to DataTable and pass the table to DataGrid.ItemsSource. For simple data (int, double, string, etc.) this will be enough.