MVVM DataContext Question
-
vendredi 3 août 2012 22:00
Hello,
I'm new to MVVM and I'm trying to understand how the relationships between user controls work. Let's say I have user control A, which has a dataContext of it's VM (call it A_VM). Serval ui elements on A are bond to A_VM. Now I have user control B, which contains an instance of A. I want to bind some of A's properties to B using xaml. How would I do this if they are all in A_VM? Do I need to then set the datacontext of A_VM to B?
Thanks,
Eric
Toutes les réponses
-
vendredi 3 août 2012 22:47Modérateur
You'd typically expose them as dependency properties in the "A" user control.
That being said, if it's purely a matter of "B" owning "A", the B's VM can own the A VM, and use the properties directly (without binding), as another option.
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marqué comme réponse Sheldon _XiaoModerator vendredi 17 août 2012 07:12
-
vendredi 3 août 2012 23:00
If I put the dependency properties in A, won't A need two DataContext's, B and A_VM?
Eric
-
vendredi 3 août 2012 23:38Modérateur
No - you can still bind to a DP even if the data context is set.
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". -
dimanche 5 août 2012 20:37
Binding uses DataContext Property as the Root object. Path experssion in the Binding is relative to this root object empty or . points the datacontext. In a control hierarchy if most inner control datacontext is NULL the binding look the parent controls datacontext, if it s NULL again then parent and parent and so until find the first non null datacontext. In your example B contains A; if you set datacontext to B then A can also use it if you dont set datacontext for a. So you can acess B model from A then you can bind the same property on the model both on A or B.
For example a control in B is a label another control in A is textbox if they both have same binding then both are syncronized when a change occurs on any where on controls or model.
Another option is to bind your inner user control(A) datacontext in outcontrol(B) markup this time AModel instance will be property of B model.
- Proposé comme réponse Sheldon _XiaoModerator vendredi 17 août 2012 07:12

