WPF 应用程序 OnExit 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23908844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:48:12  来源:igfitidea点击:

WPF application OnExit event

c#wpffunction-exit

提问by Gab

I have a WPF application with a main Window.

我有一个带有主窗口的 WPF 应用程序。

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

在 App.xaml.cs 的 OnExit 事件中,我想使用我的 MainWindow 代码中的一个方法......

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 ?

但是我在“_mainWindow.DoSomething();”上放了一个断点 当我按 f11 时,它没有进入函数,函数什么也不做......我错过了什么吗?

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

我是初学者,可以做我需要的吗?

EDIT : post edited

编辑:帖子编辑

回答by RazorEater

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.

您将 _mainWindow 声明为 Window 类。Window 类没有 DoSomething 函数。将 _mainWindow 的类更改为 MainWindow,它应该可以工作。

 public partial class App
{
    private MainWindow _mainWindow;

    ...
}

回答by Dhaval Patel

your app.cs shoule look like

你的 app.cs 看起来像

 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();
    }
}

回答by Markus

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

类 Window 没有成员 DoSomething,类 MainWindow 有(派生自 Window)。

Either change

要么改变

private Window _mainWindow;

to

private MainWindow _mainWindow;

or cast your method call like this

或者像这样投射你的方法调用

((MainWindow)_mainWindow).DoSomething();