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.
52d4f78f-b4d5-4887-bca0-7311b67fe2f0|0|.0
Tags:
C# | WPF