Understand WPF Window Events

后端 未结 2 1004
花落未央
花落未央 2020-12-08 03:22

I see Windows have a Loaded event, but not a Loading event (as there is Closing and Closed events).

My expectatio

相关标签:
2条回答
  • 2020-12-08 03:54

    Here's a simplified version of what I do (error handling removed). If the initialization takes a while, you may want to display a splash screen while you're doing your thing.

    App.xaml:

    <Application x:Class="MyProgram.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 Startup="App_StartUp" >
    </Application>
    

    App.xaml.cs:

    namespace MyProgram
    {
        public partial class App : Application
        {
            private void App_StartUp(object sender, StartupEventArgs e)
            {
                // Create the model and MainWindow
                MyModel model = CreateModel();
                MainViewModel viewModel = new MainViewModel(model);
                MainWindow = new MainWindow(viewModel); // Sets the DataContext
    
                // Do things, like initialize your model
                model.Initialize();
    
                // Now show your window
                MainWindow.Show();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-08 04:00

    You can override OnStartup() in App.xaml.cs, and do stuff before calling base.OnStartup(e);. I just checked and this is fired before the window's constructor.

    Alternatively, set the window's visibility to Hidden in its xaml file, do your initialization in the constructor and then set the visibility to Visible once done. This won't remove the delay, but the delay is only caused by whatever your initialization code is doing, so it's unavoidable unless you go asynchronous.

    0 讨论(0)
提交回复
热议问题