【问题标题】:UWP XAML User control static properties vs instance propertiesUWP XAML 用户控件静态属性与实例属性
【发布时间】:2017-11-17 20:22:46
【问题描述】:

所以我创建了一个用户控件,并在其上创建了一个依赖属性 TestProperty。

我想拥有此用户控件的 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);
}

在控件上,则设计人员无法识别该属性存在并创建错误,但在运行时该控件可以正常工作,并且该控件的每个实例都具有测试属性的正确值。

所以问题是如何让实例依赖属性在设计器中工作?

谢谢

【问题讨论】:

    标签: c# xaml uwp dependency-properties


    【解决方案1】:

    DependencyProperty 注册到 Type,而不是实例。您正确地编写了此代码来注册它。 Reference from here.

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

    然后你说,

    那么显然我不能在每个实例中为它设置不同的值

    这不是真的。

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

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

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 1970-01-01
      • 2016-07-25
      • 2011-08-03
      • 2016-04-06
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多