How to control DataContext hierarchy?


as part of a larger silverlight 4 application have a number of usercontrols encapsulate repetitive functionality. each usercontrol has own datacontext , built on mvvm pattern using data binding , command execution (icommand). these usercontrols work expected.

each usercontrol has one or more dependencyproperties defined binding data container holding controls.

finally, usercontrol inserted application page. application page built on mvvm pattern using its own datacontext to handle data binding , command execution. with "normal" controls textblock data binding page's datacontext works expected.

however, when bind 1 of dependency properties on inserted usercontrol to source property on page's datacontext things fail. silverlight goes looking the source property in usercontrols' own datacontext instead of in page datacontext. after reading we find data binding activity goes datacontext closest in hierarchy, hence usercontrol's dependency properties attempt bind usercontrol's datacontext.

now question simple; how route binding of usercontrol properties containg page's datacontext instead?

thanks input,

mike

option1:

you set usercontrol.datacontext specifically. default take datacontext of container.  override setting datacontext on usercontrol.

<<local:yourcontrol datacontext="{binding datacontext, elementname=layoutroot}" yourproperty="{binding thepropertyyouwanttobind}" />

option2:

you set binding on control this:

<local:yourcontrol  yourproperty="{binding path=datacontext.thepropertyyouwanttobind, elementname=layoutroot}"  .../>

you use elementname point control (such layoutroot of page) has datacontext want use.



Silverlight  >  Programming Silverlight with .NET – General



Comments

Popular posts from this blog

Motherboard replacement

Cannot create Full Text Search catalog after upgrading to V12 - Database is not fully started up or it is not in an ONLINE state

Remote Desktop App - Error 0x207 or 0x607