简体   繁体   中英

How to run MainWindow_Loaded from App.xaml.cs?

I have a WPF app, in file Main.xaml.cs I have the following constructor:

   public MainWindow()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

from another class:

In App.xaml.cs

I need to fire an event which will make run method MainWindow_Loaded in Main.xaml.cs

Any idea how to do it?

You can do this by manually creating the MainWindow in your App class. To do it, remove the StartUp attribute from the App.xaml so that it looks like this...

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

In your App.xaml.cs class, override the OnStartup method like this...

  public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow mw = new MainWindow();
            mw.Loaded += mw_Loaded;
            mw.Show();
        }
        void mw_Loaded(object sender, RoutedEventArgs e)
        {   // loaded event comes here
            throw new NotImplementedException();
        }
    }

This override manually creates the MainWindow and shows it. It also subscribes to the Loaded event and receives the notification in the mw_Loaded method. You can also call the window's method directly because you have the window instance.

Alternatively, you can overload the MainWindow constructor and pass it an Action delegate. It would look like this...

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        MainWindow mw = new MainWindow(DoSomething);
        mw.Show();
    }
    public void DoSomething()
    {
    }
}

And the MainWindow would look like this...

public partial class MainWindow
{
    private readonly Action _onLoaded;
    public MainWindow(Action onLoaded)
    {
        _onLoaded = onLoaded;
        InitializeComponent();
        Loaded += MainWindow_Loaded;
    }
    void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        _onLoaded();
    }
}

That gives you two alternatives, there are other ways also, but these are the most expedient. As Sheridan pointed out, tinkering with a window's loaded event can have confounding side effects, like re-entrancy. The WPF forefathers envisioned it as a lifetime event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM