C# 如何从app.xaml访问当前viewmodel

C# 如何从app.xaml访问当前viewmodel,c#,wpf,C#,Wpf,当程序关闭时,我想保存对数据的任何更改。目前,我在ViewModel中有一种方法可以执行此操作。我在app.xaml文件中有一个OnExit方法,但是如何从这里访问ViewModel中的save方法 App.xaml.cs protected override void OnExit(ExitEventArgs e) { //This is were I want to access the ViewModel base.OnExit(e);

当程序关闭时,我想保存对数据的任何更改。目前,我在ViewModel中有一种方法可以执行此操作。我在
app.xaml
文件中有一个
OnExit
方法,但是如何从这里访问ViewModel中的save方法

App.xaml.cs

    protected override void OnExit(ExitEventArgs e)
    {
        //This is were I want to access the ViewModel

        base.OnExit(e);
    }
    public void Save(){
        //This method save to the DB
    }
ViewModel.cs

    protected override void OnExit(ExitEventArgs e)
    {
        //This is were I want to access the ViewModel

        base.OnExit(e);
    }
    public void Save(){
        //This method save to the DB
    }

考虑使用观察者模式。 将视图模型注册为应用程序关闭事件的订户。 当应用程序的关闭事件被触发时,通知您的订户(即查看模型),以便他们能够对该事件作出反应

  • Prism提供了一个EventAggregator

  • Forms提供了一个消息中心

  • Bizmonger提供了一个MessageBus


您可以使用指定的中介来管理发布者/订阅模型,而不必让类相互了解。

请添加代码。。。。我们应该看什么?