简体   繁体   中英

UWP XAML User control static properties vs instance properties

So I have created a User Control and I have created a dependency property on it TestProperty.

I want to have 2 instances of this User Control and set TestProperty to a different value for each instance.

<widgets:mycontrol Test="val1"></widgets:WTComboBox>
<widgets:mycontrol Test="val2"></widgets:WTComboBox>

If I create testproperty as a static DependencyProperty as follows:

 public static readonly DependencyProperty TestProperty=
        DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null);

in the control, then obviously I can't have a different value for it in each instance, but when I create testproperty as a normal instance property

public DependencyProperty TestProperty;

public mycontrol()
{
    TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null);
}

on the control, then the designer doesn't recognise the property exists and creates an error, but at runtime the control works perfectly and each instance of the control has the right value for the test property.

So the question is how do I get instance dependencyproperty's to work in the designer?

Thanks

DependencyProperty is registered to a Type , not an instance. You correctly writes this code to register it. Reference from here.

public static readonly DependencyProperty TestProperty=
    DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null);

Then you said,

then obviously I can't have a different value for it in each instance

This is not true.

You can have different value for each instance, event though DependencyProperty is registered in this way, it isn't a static property which can only have one value for all instances of the type, like what you might have excepted the regular CLR property. To understand the differences between Dependency Property and CLR property, see this answer .

Then you define a non-static dependency property (and ask how to make the designer recognise this property), you should not do this. There are already some answer for why you should not write a non-static dependency property even if it can seemingly work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM