Changing the DataContext before a control is loaded will not work

by Geert 7. September 2010 10:00

Since some time, I am working on Catel, and open-source enterprise library with a MVVM-framework. One of the user controls that is developed for Catel is a generic UserControl that solves the nested controls problem of MVVM.

However, for this to work, I needed to change the DataContext, and what better event to use than the DataContextChanged event. However, when the control was loaded, the DataContext was set to the right type (the view model), but the bindings were still trying to bind to the model instead of the view model.

Desperately as I was, I posted this on the MSDN forums. But, too badly, no-one could help me out, so I decided to have a dream that explained to me that I had to walk around the house 3 times during full moon.

Then I thought: hey, the control is not yet loaded, maybe I should try to change the data context after I the control is loaded. And, this seems to solve the problem. You will get binding errors once (since at the initial load, the bindings are still trying to bind to the model), but after you set the datacontext to the viewmodel, all works like a charm.

So, keep in mind: you can only change the datacontext of a control when IsLoaded is true.

Explanation why you cannot change the datacontext when a control is not yet loaded

Tags:

C# | WPF

Comments are closed

About the Author

Geert van Horrik is a independent freelance software developer since January 1st, 2007. Since then he was been working on several projects from C++ to C# (WPF, ASP.NET, etc). Currently he loves to write his software using WPF (or Silverlight if WPF isn't an option).

Lately, Geert is spending a lot of time on Catel, a free open-source MVVM Framework for WPF and Silverlight. Actually, it's more than "just" an MVVM Framework, it's a complete application library!