The Situation
I’m getting the following inconstant behavior on my application: One in about 20 executions, a WPFToolkit’s DataGrid which is bound to a DataTable won’t render all the rows, missing anything between 1 to 3 of the whole 4 rows that were expected.
Inner Workings
- The
DataGridis bound to aDataTable, D1, which is a property of a custom class, C1. - When the user stimulates the view, we must retrieve the data from the back-end, which can take time. To do so, we create a thread (actually, we use
BackgroundWorkerfor that but there seems to be no difference from using one or the other), which runs a method, M1, that opens the connection and request the data. The thread is used to avoid having an unresponsive application. - M1 retrieves data and stores it on a DTO first. After that, he asks C1 to clear it’s table. C1 does so (by calling a
D1.Clear()) and raisesNotifyPropertyChanged()(from the thread). - M1 passes the new backend’s
DataTableto C1, which inserts row by row into D1. After finishing inserting the rows, C1 raisesNotifyPropertyChanged(). The thread exits.
So, in other words, I clear the table, notify WPF, insert the data, notify WPF and exit.
In my view, as long as the last Notify is correctly consumed from the UI, it should always show all the rows.
Besides the DataTable, there are a large number of properties (mostly strings and int) being update and thus notified. We have not observed this behavior in any other case, only with the DataTable.
I know this goes deep into WPF mechanisms for binding, but I hope anyone can shed a light here. Any information about WPF binding or multi-threading with WPF is welcome.
DataTable pre dates WPF and thus doesn’t implement INotifyCollectionChanged which is how WPF monitors for collection changes. You have two options:
INotifyPropertyChanged notifies when the property has changed, not when the internal state (be it a property or collection) have changed. When you fire the Property Changed event WPF only rebinds the controls if the property is a different object from the last time it bound the data. This keeps it from refreshing the whole screen when you only change one property several layers down in an object graph.