Search code examples
wpfuser-controls

WPF User Control loading twice


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.


Solution

  • 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