Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loaded event of a WPF user control fires more than once

To implement a tab-based environment in WPF we need to convert our forms to user controls, however when doing this, the Loaded event of the user control is called two times.

While searching on the internet other people also pointed this issue. How can we ensure that loaded event is called only once? Because when it is called multiple times, initialization of our controls happens multiple times.

like image 429
Muhammad Akhtar Avatar asked Aug 06 '10 05:08

Muhammad Akhtar


2 Answers

As explained in this blog, the Loaded event is fired when ever a control is about to be rendered (i.e. added to the visual tree).

There are several controls that would cause your control to be loaded/unloaded multiple times. For example, the native WPF TabControl only renders the content of the selected tab. So when you select a new tab, the content of the previously selected tab is unloaded. If you click back to the previously selected tab, then it's content is reloaded.

One work around is to use a Boolean to flag whether you have already initialized your control, as suggested by others. Alternatively, you may be able to use the Initialized event instead.

like image 185
CodeNaked Avatar answered Oct 02 '22 12:10

CodeNaked


Your routed event handler can (and should) remove itself from the Loaded hook as the first thing it does.

public class MyClass : Window
{
    public MyClass()
    {
        Loaded += MyLoadedRoutedEventHandler;
    }

    void MyLoadedRoutedEventHandler(Object sender, RoutedEventArgs e)
    {
        Loaded -= MyLoadedRoutedEventHandler;
        /// ...
    }
};
like image 32
Glenn Slayden Avatar answered Oct 02 '22 12:10

Glenn Slayden