2017-06-15 46 views
0

所以我创建了一个用户控件,并且我在它上面创建了一个依赖属性TestProperty。UWP XAML用户控件静态属性与实例属性

我希望有2个此用户控件的实例并为每个实例设置TestProperty为不同的值。

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

如果我创建testproperty为静态的DependencyProperty如下:

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

,那么显然我不能在每个实例的一个不同的值,但是当我创建testproperty作为一个正常的实例属性

public DependencyProperty TestProperty; 

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

上的控制,那么设计师不能识别属性存在,并创建一个错误,但在运行时控制完美的作品一nd控件的每个实例都具有测试属性的正确值。

所以问题是我如何获得实例dependencyproperty的工作在设计器?

感谢

回答

1

DependencyProperty注册到一个类型,而不是一个实例。您正确写入此代码进行注册。 Reference from here.

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

然后你说,

那么显然我不能在每个实例

这是不是真的为它不同的值。

你可以为每个实例不同的值,但事件被DependencyProperty以这种方式注册的,它不是一个静态属性只能有该类型的所有实例的一个值,就像你可能除外常规的CLR属性。要了解依赖属性和CLR属性之间的区别,请参阅this answer

然后你定义一个非静态的依赖项属性(并询问如何让设计者识别这个属性),你不应该这样做。已经有some answer为什么你不应该写一个非静态的依赖属性,即使它看起来可以工作。