Silverlight / WPF - Binding Datatable to a datagrid in WPF

Asked By Mitu N on 25-May-15 04:58 PM

Hi All,

I have a view model in my C# 4.0 app which has a System.Data.DataTable that's created in it using a service call. I want to bind this to a datagrid in my XAML file.

I tried following line DataGrid_Loaded event but its getting fired up before my datatable gets created inside the view model.

xaml:

<dg:DataGrid Name="myDataGrid" Loaded="DataGrid_Loaded"/>

xaml.cs:

myDataGrid.ItemsSource = myViewModel.myDataTable.DefaultView;

Thanks.
Robbe Morris replied to Mitu N on 26-May-15 08:01 AM
You are going to have better all around binding results if you create an ObservableCollection<MyDataClass> and load it with a custom class that has properties for each of your DataTable columns.  Then, load the collection.

If you create a property on your ViewModel of this ObservableCollection and create a new instance of it (versus leaving it null).  Bind your datagrid to it.  Later, when the ObservableCollection gets loaded, the binding will automatically refresh and draw the datagrid with your data in it.