【问题标题】:Accessing Dependency Property on Load在加载时访问依赖属性
【发布时间】:2012-03-28 23:08:14
【问题描述】:

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

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。加载控件后,我可以访问我设置的任何值。如何在控件的构造函数中访问此值?谢谢

【问题讨论】:

  • XAML 相当于做:new VisitationHours() { RuleTypeId = 2 };。请注意初始化程序,其中 RuleTypeId 没有通过 ctor 发送。尝试其他路径。

标签: wpf properties dependencies


【解决方案1】:

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

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 事件。

【讨论】:

  • 谢谢,我最终为它写了一个活动。
  • 对有关OnInitialized 的有用提醒进行小幅更正:在某些情况下,该功能可能不一定显示为override,因为(至少,例如)DependencyObjectDispatcherObject 和其他类型不声明它。幸运的是,XamlObjectWriter(和其他初始化/反序列化基础设施?)寻找的基本要求是ISupportInitialize。对于这种情况,只要在 XAML 根对象(其 Result)上检测到该接口(或派生的 ISupportInitializeNotification),XamlObjectWriter 将正确调用 BeginInit / EndInit
猜你喜欢
  • 1970-01-01
  • 2018-08-12
  • 2018-11-14
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 2011-07-09
相关资源
最近更新 更多