c# - How to bind a child `UserControl`'s Dependency Property, using `Style`, to a property of the host element's view-model? -
how bind child usercontrol
's dependency property, using style
, property of host element's view-model?
i tried code below, , myblock.blockisonlyone
should bound view-model's property - mycontainerviewmodel.viewmodelisonlyone
, via style
's setter
. reason doesn't work - myblock.blockisonlyone
's value never changes, although mycontainerviewmodel.viewmodelisonlyone
changes...
the container xaml:
<usercontrol x:class="myns.mycontainer" ... > <usercontrol.datacontext> <vc:mycontainerviewmodel x:name="thedatacontext"/> </usercontrol.datacontext> <grid> <grid.resources> <style targettype="{x:type vc:myblock}"> <setter property="blockisonlyone" value="{binding viewmodelisonlyone}"/> <!-- tried too, no success: --> <!-- <setter property="blockisonlyone" value="{binding viewmodelisonlyone, elementname=thedatacontext}"/> --> </style> </grid.resources> ... <vc:myblock datacontext="{binding porta[0]}" /> </grid> </usercontrol>
the container's viewmodel
(only important part...):
[notifypropertychangedaspect] // handles inotifypropertychanged implementation... class mycontainerviewmodel{ ... public bool viewmodelisonlyone { get; private set; } ... }
the myblock
usercontrol
:
class myblock : usercontrol{ ... public static readonly dependencyproperty blockisonlyoneproperty = dependencyproperty.register( "blockisonlyone", typeof (bool), typeof (myblock), new propertymetadata(default(bool), blockisonlyone_propertychangedcallback)); private static void blockisonlyone_propertychangedcallback(dependencyobject dependencyobject, dependencypropertychangedeventargs a) { var @this = dependencyobject myblock; if (@this == null) return; trace.writeline(string.format("old: {0}, new: {1}", a.oldvalue, a.newvalue)); // never seems fire... } public bool blockisonlyone { { return (bool) getvalue(blockisonlyoneproperty); } set { setvalue(blockisonlyoneproperty, value); } } ... }
you should able reach view model property usercontrol
using relativesource binding
. idea search parent view view model set datacontext
using ancestortype
property... try this:
<style targettype="{x:type vc:myblock}"> <setter property="datacontext.blockisonlyone" value="{binding viewmodelisonlyone, relativesource={relativesource ancestortype={x:type usercontrol}}}" /> </style>
if picks child usercontrol.datacontext
instead, either set relativesource.ancestorlevel
property appropriate level, or use name/type of parent usercontrol
instead:
<style targettype="{x:type vc:myblock}"> <setter property="blockisonlyone" value="{binding datacontext.viewmodelisonlyone, relativesource={relativesource ancestortype={x:type yourprefix:mycontainer}}}" /> </style>
Comments
Post a Comment