wpf - setting dependency property in user control style -
i implemented user control dependency property looks this:
public partial class myuc : usercontrol, inotifypropertychanged { public static readonly dependencyproperty mybackgroundproperty = dependencyproperty.register("mybackground", typeof(brush), typeof(myuc), new frameworkpropertymetadata(brushes.white, frameworkpropertymetadataoptions.affectsrender)); public brush mybackground { { return (brush)getvalue(mybackgroundproperty); } set { setvalue(mybackgroundproperty, value); } } //... }
and try set property in xaml follows:
<usercontrol x:class="custom.myuc" x:name="myucname" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:custom" mc:ignorable="d" tabindex="0" keyboardnavigation.tabnavigation="local" horizontalcontentalignment="left" verticalcontentalignment="top" mouseleftbuttondown="onmouseleftbuttondown"> <usercontrol.style> <style targettype="local:myuc"> <setter property="mybackground" value="black"/> </style> </usercontrol.style> <border borderthickness="0"> //... </border> </usercontrol>
it compiles when run app following exception:
set property 'system.windows.setter.property' threw exception.' line number '..' , line position '..'."
how can solve this?
the problem arises because you're trying apply style targettype="myuc" element of type usercontrol.
the solution apply style outside of control. example when use control in window:
<window.resources> <style targettype="local:myuc"> <setter property="mybackground" value="red" /> </style> </window.resources> <grid> <local:myuc /> </grid>
as test added code user control:
public partial class myuc { public myuc() { initializecomponent(); } public static readonly dependencyproperty mybackgroundproperty = dependencyproperty.register("mybackground", typeof(brush), typeof(myuc), new propertymetadata(brushes.white, propertychangedcallback)); private static void propertychangedcallback(dependencyobject dependencyobject, dependencypropertychangedeventargs dependencypropertychangedeventargs) { ((myuc)dependencyobject).mybackgroundpropertychanged( (brush)dependencypropertychangedeventargs.newvalue); } private void mybackgroundpropertychanged(brush newvalue) { background = newvalue; } public brush mybackground { { return (brush)getvalue(mybackgroundproperty); } set { setvalue(mybackgroundproperty, value); } } }
which results in control having red background.
Comments
Post a Comment