Search code examples
wpfmvvmdata-bindingdatatablewpfdatagrid

WPF: Refreshing DataGrid after columns changed in DataTable, MVVM way


I am using vanilla WPF Datagrid that has its ItemsSource bound to a DataTable:

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding ResultTable.DefaultView}" >

Where ResultTable is the DataTable. I have tried adding rows programmatically at runtime and the DataGrid will update accordingly. However, the DataGrid does not update When I add or remove columns at runtime. Here is what I have in my ViewModel

class MyViewModel : ObservableObject
{
    private DataTable resultTable;
    public DataTable ResultTable
    {
        get { return resultTable; }
        set
        {
            resultTable = value;
            RaisePropertyChanged("ResultTable");
        }
    }

    public void AddColumn(string columnName)
    {
        ResultTable.Columns.Add(columnName);
    }
}

I found an almost identical question here WPF Datagrid using MVVM.. is two way binding to DataTable possible? but there did not seem to be a conclusive answer. Unfortunately, the person who asked the question seemed to have found a workaround but did not bother to post it...

I also found a solution here http://www.mikeware.com/2012/08/datagrid-dilemma/ but it appears very "hackish" (not to mention non-MVVM) and the author himself admits that he would prefer to do it another way if he found one.

How can I force the DataGrid to update when I add new columns? I prefer to do it in a MVVM way if possible.


Solution

  • First add this code to ViewModel:

    private static readonly DataTable _dt = new DataTable();
    

    Then you can add that what like this code when you add column:

    public void AddColumn(string columnName)
    {
        var temp = this.ResultTable;
        this.ResultTable = _dt;
        temp.Columns.Add(columnName);
        this.ResultTable = temp;
    }