If we have customized a usercontrol, we may need to define some dependency attributes unique to this user control.
However, in some cases, we may want to reuse the dependency attribute of the parent control. For example, if a control is called mycontrol, the root container in the control is layoutroot. In XAML, I want to define it as follows: <UC: mycontrol background = "white"/>, and then the layoutroot background is assigned white.
One way is to redefine the dependency attribute of background to overwrite the original background attribute, register the propertychanged event, and assign the background value to layoutroot when the event is triggered.
Another method is simpler. layoutroot can bind elementname to the value of mycontrol's background to change the background.
ImplementedCodeAs follows:
<Usercontrol X: class = "testproject. controls. mycontrol "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: D =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: MC =" http://schemas.openxmlformats.org/markup-compatibility/2006 "MC: ignorable = "D" background = "black" X: Name = "parentctl"> <grid X: Name = "layoutroot" background = "{binding background, elementname = parentctl} "/> </usercontrol>
We can use it like this:
<UC: mycontrol X: Name = "mycontrol" background = "white"/>
If we only define mycontrol but do not define the value of background, it uses the default value (the default value in this example is black, as shown in the Code ).