I found an easier way to do it.
Instead of setting the dataGrid to AutoGenerateColumns, i set a property notifier to ItemsSource of the dataGrid, then fill it with a direct cast to IEnumerable< object > then used the ToList() extension.
Whenever my datasource is changed, im adding the columns manually, with its proper headers and bindings.
Now Im able to sort the rows by clicking on the column header.
Code:
...
dataGrid1.ItemsSource = (IEnumerable<object>)methodQuery.Invoke(instance, parameters).ToList();
...
...
private void DataGridItemsSourceChanged(object sender, EventArgs e)
{
var currentDataGrid = (DataGrid)sender;
foreach (TSpe_Reg reg in tabItemSourceChange.TSpe_Reg) // tabItemSourceChange is used to check the table and field names, since im using reflection.
{
string headerName = "";
if (reg.a_short_name != "")
headerName = reg.a_short_name;
else
headerName = reg.a_full_name;
string boundColumn = "a_" + reg.a_field_name + "_" + tabItemSourceChange.a_table_name;
DataGridTextColumn ColumnDataGrid = new DataGridTextColumn { Header = headerName, Binding = new Binding(boundColumn) };
}
}
// Calls the DataGridItemsSourceChanged whenever the DependencyProperty ItemsSource is changed.
private void CallItemSourcePropertyDescriptor(DataGrid currentDataGrid)
{
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(DataGrid));
if (dpd != null)
{
dpd.AddValueChanged(currentDataGrid, DataGridItemsSourceChanged);
}
}