I got a problem with the designpattern MVVM.
In my View i got a Datagrid with an binding to a datatable in my viewmodel.
<WPF:BADataGrid Grid.Column="1" x:Name="dgStapelliste" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Stapelliste, Mode=OneWay}"/>
In my constructor of the viewmodel I load the ItemsSource.
this.StapelListe = this._stapel.Get();
If I add some additional rows during runtime via a button everything works fine.
But I don´t want to push a button to refresh the datagrid, I want it to happen automatically in a thread or background worker.
Here´s some test example:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
while (true)
{
Thread.Sleep(5000);
DataRow row = this.StapelListe.NewRow();
row["StapelNr"] = 123456;
this.StapelListe.Rows.Add(row);
}
};
THIS won´t work… and I don´t know why… the rows are added in the datatable “StapelListe” but the datagrid is not going to refresh itself…
If I change an existing row in the datatable in a thread it works! It just doesn´t work with adding or removing rows from the collection.
Someone got an idea why this happens and/or how to resolve it?
Kind regards…
As MegaMind wrote, the View needs to know that something has changed. If you are adding new Rows to an existing DataTable, the View never gets notified that something has been added. So you should use a collection which was made for that:
ObservableCollection<T>.