GibboK
GibboK

Reputation: 73908

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?

Upvotes: 0

Views: 3812

Answers (1)

Gayot Fow
Gayot Fow

Reputation: 8792

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.

Upvotes: 3

Related Questions