Loaded event of a WPF user control fires more than once

前端 未结 3 1984
忘掉有多难
忘掉有多难 2020-12-05 01:54

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 use

相关标签:
3条回答
  • 2020-12-05 02:40

    Set a loaded flag in the event, and, if the flag has already been set, don't do anything.

    0 讨论(0)
  • 2020-12-05 02:42

    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.

    0 讨论(0)
  • 2020-12-05 02:42

    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;
            /// ...
        }
    };
    
    0 讨论(0)
提交回复
热议问题