c# - WPF Cascading Binding -
topic: how prevent binding on usercontrol overrides binding given upper (main)window using usercontrol.
i read posts, , books on subject still puzzled binding mechanisms. in specialized books terms of dependencyproperty or attachedproperty barely mentioned. microsoft documentation bare.
thanks putting me again on right direction
this example extreme simplification of basketballroster mvvm example of head first c#
i have usercontrol, simple circle
... xmlns:vm_nmspc="clr-namespace:bindingmcve.viewmodel" > <usercontrol.resources> <vm_nmspc:my_usercontrol_vm x:key="myusercontrolvm"/> </usercontrol.resources> <grid> <stackpanel datacontext="{dynamicresource resourcekey=myusercontrolvm}" height="100" width="100"> <ellipse fill="{binding my_color}" height="50" width="50"/> </stackpanel> </grid>
and provide parameterless contructor my_usercontrol_vm() can view circle filled red while working on view of usercontrol.
for use instance of class my_usercontrol_vm inside usercontrolresources. here use dynamicresource keyword ( had first tested staticresource )
class my_usercontrol_vm { public string my_color {get; set;} public my_usercontrol_vm() : this("red") { } public my_usercontrol_vm(string color) { my_color = color; } }
now want use several usercontrol inside (main)window, still using binding see in "real time" evolution of view.
xmlns:vm_nmspc="clr-namespace:bindingmcve.viewmodel" > <window.resources> <vm_nmspc:main_window_vm x:key="mainwindowvm"/> </window.resources> <grid> <stackpanel datacontext="{dynamicresource resourcekey=mainwindowvm}"> <view_nmspc:usercontrol1 datacontext="{binding usr_ctrl_1}"/> <view_nmspc:usercontrol1 datacontext="{binding usr_ctrl_2}"/> </stackpanel> </grid> </window>
and viewmodel class dedicated mainwindow
class main_window_vm { public my_usercontrol_vm usr_ctrl_1 { get; set; } public my_usercontrol_vm usr_ctrl_2 { get; set; } public main_window_vm() { usr_ctrl_1 = new my_usercontrol_vm("green"); usr_ctrl_2 = new my_usercontrol_vm("blue"); } }
note expecting see green , blue filled circles.
however red circles
i have got green , blue circle had not put resource inside usercontrol
while using debugger can see entering first constructor of class main_window_vm , after (2 times) 1 of class my_user_control_vm, both circles red.
i know @ present time maybe 10% aware of wpf thought way of doing have been quite right. last requesting inside mainwindow usercontrol1 control be bind property usr_ctrl_x of class main_window_vm
any advice welcome.
best regards.
ngi
you setting datacontext
of usercontrol
, isn't used ellipse
inherits datacontext
of stackpanel
. doesn't change , bound myusercontrolvm
resource.
you should remove datacontext="{dynamicresource resourcekey=myusercontrolvm}"
stackpanel
. if add usercontrol
binding should overwrite it. use blend design namespaces set design datacontext
used @ design time.
Comments
Post a Comment