1
votes

I have a datagrid in my View with it's ItemSource bound to a DataTable in my ViewModel. When I update the DataTable programmatically (adding a column through a command) the changes are not populated to the View. Also, if I invalidate the View, by switching to another tab and then switching back, the changes made are shown.

My ViewModel inherits from INotifyPropertyChanged, and I am raising the PropertyChanged event correctly since I use the same process for other bound properties in the ViewModel and they work as expected.

Is it possible to get the datagrid to reflect changes I've made to the bound DataTable using the MVVM pattern?

Is there a datagrid event I can use to refresh the datagrid in the view's code behind?

Thanks for your help! -Steven

2

2 Answers

2
votes

While modifying rows and editing cell contents in the DataTable get reflected in the DataGrid (works for me) you're right that ColumnChanges don't seem to be. If you're using the AutoGenerateColumns option then I imagine it does so at initialization but doesn't watch for changes afterwards.

If you can find an event which fires (I haven't noticed one) when a column is added to the DataTable you could then add it manually in the code behind. Another hack which may or may not be practical would be to set your DataTable propety to null, and then re-set your property to the DataTable, with OnPropertyChanged being called each time. That should force the rebuilding of the DataGrid.

private DataTable _myDataTable;

public DataTable MyDataTable
{
   get { return _myDataTable; }
   set
   {
        _myDataTable = value;
        OnPropertyChanged("MyDataTable");
   }
}

void SomeMethod()
{
     ....results in column changes
     DataTable holder;
     holder = MyDataTable
     MyDataTable = null;
     MyDataTable = holder;         
}
1
votes

You must use ObservableCollection<> type to binding with DataGrid. Until do this, your DataGrid can update the change of DataTable in ViewModel.

Raising the PropertyChanged event seem useless when you bind with the type rather than ObservableCollection<>.