Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
2395
Switching tabs triggeers Unloaded event ?!?
posted

Hi,

 

Switching tabs triggers an Unload event on the control hosted by the "old" tab. Consequently this causes a Loaded event when switching back.

 

This is bad in case of controls

a) which have a heavy weight initialization when then would be called multiple times on tabbing back and forth

b) which needed some "shutdown" logic which usually is placed in the Unloaded event handler (I'm not aware of any other event which would only be called once on "shutdown")

 

How could the above behavior be prevented?

 

Thanks

Parents
  • 54937
    Suggested Answer
    Offline posted

    Dierk said:
    Switching tabs triggers an Unload event on the control hosted by the "old" tab. Consequently this causes a Loaded event when switching back.

     This will happen anytime you have an element that is in the visual tree and it is removed from the visual tree for a period of time. It just happens that the TabControl (xamTabControl derives from TabControl) only keeps the Content of the selected TabItem in the visual tree (i.e. within the ContentPresenter within the template). The Content of the previously selected tab is removed from that contentpresenter so that the content of the new one can be displayed. This results in the Unloaded event occurring.

    Dierk said:
    a) which have a heavy weight initialization when then would be called multiple times on tabbing back and forth

    If this is one time initialization then you could keep a flag and only do your initialization the first time you get the Loaded event.

    Dierk said:
    b) which needed some "shutdown" logic which usually is placed in the Unloaded event handler (I'm not aware of any other event which would only be called once on "shutdown")

    You would probably need to walk up the visual/logical tree (i.e. using VisualTreeHelper/LogicalTreeHelper) and look for an ancestor whose IsLoaded is true (e.g. the ancestor tab control). Or check that you still have a Window reference (i.e. Window.GetWindow doesn't return null). In a TabControl, you would actually get another Unloaded once the window is actually unloaded.

     

Reply Children
No Data