문제

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