在加载时访问依赖属性

时间:2012-03-12 14:27:52

标签: wpf properties dependencies

我正在我的一个用户控件中设置自定义属性,如下所示。

C#

   public static readonly DependencyProperty RuleType1 = DependencyProperty.Register
   (
      "RuleType1", typeof(int), typeof(EmailNotification), new PropertyMetadata(0)
   );

    public int RuleTypeId
    {
        get { return (int)GetValue(RuleType1); }
        set { SetValue(RuleType1, value); }
    }

XAML

<helper:VisitationHours RuleTypeId="2" />

这很好用,除了我在控制加载之前似乎无法获得RuleTypeId。它总是变为默认值0.加载控件后,我可以访问我设置的任何值。如何在控件的构造函数中访问此值?感谢

1 个答案:

答案 0 :(得分:2)

首先,您应该修复依赖项属性的名称:

public static readonly DependencyProperty RuleTypeIdProperty =
    DependencyProperty.Register("RuleTypeId", typeof(int), typeof(EmailNotification), new PropertyMetadata(0)); 

public int RuleTypeId 
{ 
    get { return (int)GetValue(RuleTypeIdProperty); } 
    set { SetValue(RuleTypeIdProperty, value); } 
} 

然后,如果VisitationHours是要设置属性的用户控件,则答案是您无法访问控件的构造函数中的值。首先构造对象,然后由WPF设置属性。

对于必须访问属性值的代码,您可以覆盖OnInitialized或将处理程序附加到Initialized事件。