[英]At what stage in a control's lifetime can it access inherited attached properties?
I have a control that uses a certain inherited attached property, and I found that I can't access that property in the constructor, which is reasonable, since at that stage the control isn't a part of the visual tree and so it can't inherit any attached properties. 我有一个使用某些继承的附加属性的控件,但发现无法在构造函数中访问该属性,这是合理的,因为在那个阶段,该控件不是可视化树的一部分,因此可以不会继承任何附加属性。
// Constructor
public MyClassName()
{
InitializeComponent();
MyValue value = DeclaringClass.GetMyAttachedProperty(depObj); // value == null
}
When I try to access the property during the Loaded
event, I am able to retrieve the value: 当我尝试在
Loaded
事件期间访问属性时,我能够检索该值:
// Constructor
public MyClassName()
{
InitializeComponent();
Loaded += OnLoaded;
}
void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded;
MyValue value = DeclaringClass.GetMyAttachedProperty(depObj); // value != null
// Do something with value
}
So this brings me to my question - what is the earliest stage in the control's lifetime where it can access inherited attached properties? 因此,这使我想到了一个问题-控件生命周期中最早的哪个阶段可以访问继承的附加属性? Is there a better place to do so instead on the
Loaded
event? 在
Loaded
事件上是否有更好的方法呢?
The earliest possible is indeed inside the Loaded
event handler. 最早可能确实在
Loaded
事件处理程序内部。 Your only other choice is the constructor (or the morally equivalent Initialized
event) but that's too soon for dependency properties to assume inherited values. 唯一的选择是构造函数(或在道德上等效的
Initialized
事件),但是对于依赖属性而言,现在假定继承值还为时过早。
See also common object lifetime events at MSDN. 另请参见MSDN上的常见对象生存期事件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.