Question

is there a way to be notified when the visual parent of a FrameworkElement changes, without overriding the OnVisualParentChanged method, just by using events?

Here is the idea to use the "Loaded" event but this doesn't seem to be safe.

Is there an event that definitively fires when the the visual parent changes/changed?

Was it helpful?

Solution 2

This is somewhat to do with OnVisualParentChanged. In the FrameworkElement.cs implementation, it does private void TryFireInitialized(), which in turn will call protected virtual void OnInitialized(EventArgs e), so you could hook in there.

It does depend on what information you need to know. As far as I can tell, the only place to get notified that the parent is changing AND be able to access the old parent is OnVisualParentChanged (the old parent is passed in as the parameter). Otherwise any other place to hook in you will only be able to access the new parent, as it has already been changed.

You may also want to investigate some classes that inherit FrameworkElement and see if they expose any additional properties or methods that could help you.

OTHER TIPS

In my tests Loaded Unloaded do get fired when parent changes so I would say it's safe to reply on them. But, as mentioned before you can only access the old parent if you hook OnVisualParentChanged (by the time _Unloaded is called VisualParent is already null) Overriding OnVisualParentChanged is pretty simple if that was your concern.

    void _Loaded(object sender, RoutedEventArgs e)
    {
        DoSmthng();
    }

    void _Unloaded(object sender, RoutedEventArgs e)
    {
        DoSmthngElse();
    }

    protected override void OnVisualParentChanged(DependencyObject oldParent)
    {
        DoSmthngOther();

        // Call base class to perform standard event handling. 
        base.OnVisualParentChanged(oldParent);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top