Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM DataBindings stop updating

Tags:

I am working on a medium size WPF application that utilizes the MVVM pattern. ViewModels use INotifyPropertyChanged to refresh their respective Views.

This approach works perfectly, except for one problem: when this application is left running for long periods of time (3-7 days) the Views (every single View in the entire app!) suddenly stop updating their bound properties.

If I set a breakpoint in the ViewModels, they are chugging away happily, calling PropertyChanged like nothing is wrong. However, if I set a breakpoint in the getter of one of the ViewModel objects that the View is bound to, the getter is never called!

I am stumped at this point, and don't even know how to debug this issue properly. I have checked the Visual Studio output window for data binding errors, but everything looks normal. It is almost as if the WPF data binding engine has crashed in the background. This app is also monitoring unhandled exceptions (AppDomain.UnhandledException and Dispatcher.UnhandledException), but no exceptions are being thrown.

Summary: After long periods of time, the Views stop updating their data bindings, but the ViewModels are still calling the PropertyChanged event.

Any advice???

like image 793
shansen Avatar asked Sep 10 '12 15:09

shansen


2 Answers

After several months of debugging, I was finally able to solve the issue by attaching a debugger to the remote target. Only then did it produce an exception that I could debug. I still do not understand why AppDomain.UnhandledException and Dispatcher.UnhandledException did not catch this exception, but at least I was able to figure it out.

like image 152
shansen Avatar answered Oct 03 '22 18:10

shansen


You might be falling victim to over-zealous weak references. There might be a fix for your MVVM framework. If not, this information might help you find the issue in the source code.

There is a known memory leak in most implementations of INotifyPropertyChanged. The view model takes a hard reference on the delegate of the XAML control's PropertyChanged handler. That delegate in turn takes a hard reference on the XAML control. Because of this, the control can't be collected as long as the view model exists.

So to fix this problem, many MVVM frameworks use weak references for events. While this can fix the memory leak, it can also cause the problem that you are seeing. If the weak event isn't properly implemented, it might be removed before the XAML control is actually collected.

I suspect that you are using an MVVM framework with weak references, and that they are getting prematurely disposed. To see if this is a likely issue, put a few calls to GC.Collect() and see if the problem occurs more frequently.

like image 31
Michael L Perry Avatar answered Oct 03 '22 17:10

Michael L Perry