views:

277

answers:

3

Hai

am having a WPF user control, when i use that control in another window it loading twice, so its throwing exception for me, coz am having some function in usercontrol_loaded event, when it loading twice it throwing error, is there any other way to check if the usercontrol is loaded like that, else how to solve this issue.

A: 

Can you provide a code snippet?

Queso
+2  A: 

Hi

Long story short, use a boolean flag:

    private bool firstLoad = true;
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        if (firstLoad)
        {
            firstLoad = false;

            // Do somthing that want to do only once...
        }
    }

Longer story: Apparently, in WPF you can't assume the loaded event is fired only once.

I've encountered the same situation using a user control in a Tabitem. Every time you activate a Tabitem by selecting it the loaded event is fired for all controls within this tabitem.

Cheers

Hertzel Guinness
A: 

Yeah, I find this behavior really weird. Ultimately I think that what Hertzel said is the best way to go- that or deriving a new UserControl class like so:

You can derive stuff from LoadOnceUserControl and its FirstLoaded event will be called only once.

using System.Windows;
using System.Windows.Controls;
public class LoadOnceUserControl : UserControl
{
    private bool firstLoadCalled = false;

    public LoadOnceUserControl()
    {
        // Hook up our loaded event
        this.Loaded += new RoutedEvent(delegate(object sender, RoutedEventArgs e)
        {
            // If FirstLoad hasn't been called and there are events to be called...
            if (!this.firstLoadCalled && this.FirstLoaded != null)
            {
                this.FirstLoaded(sender, e);
            }

            // We've already called (or attempted to call) FirstLoad.
            this.firstLoadCalled = true;
        });
    }

    event RoutedEventHandler FirstLoaded;
}
Zane Kaminski