0

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

Incredible
  • 3,495
  • 8
  • 49
  • 77
Gab
  • 1,861
  • 5
  • 26
  • 39
  • what is myController? – Dhaval Patel May 28 '14 at 10:19
  • It's a instance of a class I have in the MainWindow : "public myController mycontroller;" , "printerController = new myController(); and I need to use this instance from the "OnExit" event. I also tried to use the "Closed" Event of the MainWindow, but when I close the window, the applications closes and the event is not fired... – Gab May 28 '14 at 10:23

3 Answers3

1

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;

    ...
}
RazorEater
  • 265
  • 2
  • 14
  • Oh... thanks. The function is now accessible. 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 ? – Gab May 28 '14 at 10:27
  • i used your code and only changed what i showed here and changed DoSomething to print something to console ( Console.WriteLine("DoSomething"); ) and it does work for me. I guess you're missing something but i cannot tell what. Maybe post more code? – RazorEater May 28 '14 at 10:35
0

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();
    }
}
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
0

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();
Markus
  • 116
  • 4