WPF application OnExit event

8.3k views Asked by At

I have a WPF application with a main Window.

In App.xaml.cs, in the OnExit event, I would like to use a method from my MainWindow code behind...

public partial class App
{
    private MainWindow _mainWindow;

    protected override void OnStartup(StartupEventArgs e)
    {
         _mainWindow = new MainWindow();
        _mainWindow.Show();


    }

    protected override void OnExit(ExitEventArgs e)
    {
        _mainWindow.DoSomething();
    }

}

The method :

public void DoSomething()
{
    myController.Function(
       (sender, e) =>
       {

        },

       (sender, e) =>
        {

        }
        );
 }

But I put a breakpoint on the "_mainWindow.DoSomething();" and when I press f11, it doesn't enter into the function and the function does nothing... Am I missing something ?

I'm a beginner, is it possible to do what I need ?

EDIT : post edited

3

There are 3 answers

2
RazorEater On BEST ANSWER

You declared your _mainWindow as the Window class. The Window class does not have a DoSomething function. Change the class of _mainWindow to MainWindow and it should work.

 public partial class App
{
    private MainWindow _mainWindow;

    ...
}
1
Dhaval Patel On

your app.cs shoule look like

 public partial class App : Application
{
    private MainWindow _mainwindow;

    public MainWindow mainwindow
    {
        get { return _mainwindow??(_mainwindow=new MainWindow()); }
        set { _mainwindow = value; }
    }
    protected override void OnStartup(StartupEventArgs e)
    {
        _mainwindow.Show();
    }
    protected override void OnExit(ExitEventArgs e)
    {
        _mainwindow.DoSomething();
    }
}
0
Markus On

Class Window does not have the member DoSomething, class MainWindow does (derived from Window).

Either change

private Window _mainWindow;

to

private MainWindow _mainWindow;

or cast your method call like this

((MainWindow)_mainWindow).DoSomething();