views:

558

answers:

1

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  A: 

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;         
}
AndyG
I found a way to make your workaround work for my scenario. I am not sure why I didn't try this myself, but in any case I appreciate your time and help.Thanks!
stevosaurus
Pleasure, happy it helped
AndyG