คำตอบ MVVM DataContext Question

  • 3 สิงหาคม 2555 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

ตอบทั้งหมด

  • 3 สิงหาคม 2555 22:47
    ผู้ดูแล
     
     คำตอบ

    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".

    • ทำเครื่องหมายเป็นคำตอบโดย Sheldon _XiaoModerator 17 สิงหาคม 2555 7:12
    •  
  • 3 สิงหาคม 2555 23:00
     
     

    If I put the dependency properties in A, won't A need two DataContext's,  B and A_VM?

    Eric

  • 3 สิงหาคม 2555 23:38
    ผู้ดูแล
     
     

    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".

  • 5 สิงหาคม 2555 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.  

     
    • เสนอเป็นคำตอบโดย Sheldon _XiaoModerator 17 สิงหาคม 2555 7:12
    •