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:

// 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?

有帮助吗?

解决方案

The earliest possible is indeed inside the Loaded event handler. 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.

See also common object lifetime events at MSDN.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top