I have a DataGrid that I fill with a DataView (using DataContext). I have tried to do that in a separate thread but the UI still freezes. I want to prevent the UI from freezing when populating the DataGrid.
Here is the code I made so far:
private void btnOK_Click(object sender, RoutedEventArgs e)
{
GetFieldsBLL getFieldsBLL = new GetFieldsBLL();
DataView dv = getFieldsBLL.GetWholeView(ViewName);
Task task = new Task(() => ucDataExtracViewControl.PopulateGrid(dv));
task.Start();
}
public void PopulateGrid(DataView dv)
{
dgView.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate{
dgView.Columns.Clear();
dgView.AutoGenerateColumns = false;
foreach (DataColumn column in dv.Table.Columns)
{
var gridColumn = new DataGridTextColumn()
{
Header = column.ColumnName,
Binding = new Binding("[" + column.ColumnName + "]")
};
dgView.Columns.Add(gridColumn);
}
dgView.DataContext = dv;
DataView = dv;
}));
}
Thanks in advance!
Edit: The reason why I recreate the columns is because some of the column names have a dot in their name. For instance “Job No.” doesn’t yield any data when using binding. Read more here: What is it about DataTable Column Names with dots that makes them unsuitable for WPF's DataGrid control? It is not an option to make changes to the database. –