Set on datagrid this: AutoGenerateColumns = true. Whit this setting the datagrid creates the columns automatically in base of the object.
For sorting set this CanUserSortColumns = true.
In backend sort the list:
private List orginalSource = new List();
private List sortedItems = new List();
private Dictionary itemProperties = new Dictionary();
public List SortedItems
{
get => sortedItems;
set
{
sortedItems = value;
OnPropertyChanged();
}
}
private void InitializeList()
{
//Get list from the database
SortedItems = orginalSource = GetFromDb();
//initialize data structure to get the properties
itemProperties = new Dictionary();
var firstItem = sortedItems?.First();
if (firstItem != null)
{
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(firstItem))
{
itemProperties[propertyDescriptor.Name] = propertyDescriptor;
}
}
}
private async void DataGrid_Sorting(object sender, DataGridColumnEventArgs e)
{
if (e.Column.SortDirection != DataGridSortDirection.Ascending)
{
e.Column.SortDirection = DataGridSortDirection.Ascending;
SortedItems = orginalSource.OrderBy(x => GetDynamicValue(x, e.Column.Header.ToString())).ToList();
}
else
{
e.Column.SortDirection = DataGridSortDirection.Descending;
SortedItems = orginalSource.OrderByDescending(x => GetDynamicValue(x, e.Column.Header.ToString())).ToList();
}
//wait a little bit, that the datagrid can recreate all
await Task.Delay(10);
DataGrid dg = sender as DataGrid;
//reset sort direction of the column
foreach (var column in dg.Columns)
{
if(column.Header == e.Column.Header)
{
column.SortDirection = e.Column.SortDirection;
}
}
}
private object GetDynamicValue(dynamic item, string propertyName)
{
if (itemProperties.ContainsKey(propertyName))
return itemProperties[propertyName].GetValue(item);
else
return null;
}