Dual loading event in WPF

I had some difficulty binding data to a custom controll value made by someone else, so I used the "Loaded" event to assign the controll value in time, but I noticed that this event is fired twice.

How can I find out what a dismissal is? (VS2008) Or maybe any solution expected :)

+2


a source to share


3 answers


More than twice your loaded event will fire (mostly) every time your control becomes visible. For example, a tab control fires the Loaded event every time you switch to its tab.

Here's a simple solution:



bool m_Loaded = false;
void Loaded(object sender, RoutedEventArgs args)
{
    bool tmpLoaded = m_Loaded;
    m_Loaded = true;
    if (tmpLoaded ) return;

    // your code here...
}

      

Good luck // Jerry

+4


a source


Jerry's answer is a common twist to the problem of the Loaded event being fired every time a control is visible.

But I prefer a solution without constantly evaluating cumbersome flags: just subtract the handler from the event on first run.



In addition, you have the option to attach another handler to execute your code when the control becomes visible after the first time.

    public UserControl1()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(UserControl1FirstTime_Loaded);

    }

    void UserControl1FirstTime_Loaded(object sender, RoutedEventArgs e)
    {
        Loaded -= UserControl1FirstTime_Loaded; //This handler not called again
        ...................
        //Add next line if you want code to be executed when de control becomes visible 
        //after first time.
        Loaded +=UserControl1AfterFirstTimes_Loaded;
    }

    void UserControl1AfterFirstTime_Loaded(object sender, RoutedEventArgs e)
    {
        //Code to be executed when the control becomes visible after first time
        ....
    }

      

+2


a source


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

There are several controls that cause your control to be loaded / unloaded multiple times. For example, the built-in WPF TabControl displays only the contents of the selected tab. Therefore, when you select a new tab, the contents of the previously selected tab are unloaded. If you click on a previously selected tab, the content will reload.

+1


a source







All Articles