UWP XAML用户控制静态属性与实例属性

时间:2017-06-15 11:01:55

标签: c# xaml uwp dependency-properties

所以我创建了一个User Control,并在TestProperty上创建了一个依赖属性。

我想拥有此User Control的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);
}

在控件上,然后设计器无法识别属性存在并创建错误,但在运行时控件完美运行,并且控件的每个实例都具有测试属性的正确值。

所以问题是如何在设计器中使用实例依赖属性?

由于

1 个答案:

答案 0 :(得分: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为什么你不应该写一个非静态依赖属性,即使它看起来似乎有效。

相关问题