简体   繁体   English

如何从app.xaml访问当前视图模型

[英]How to access current viewmodel from app.xaml

When the program closes I want to save any changes to the data. 程序关闭时,我想保存对数据的任何更改。 I currently have a method to do so in my ViewModel . 我目前在ViewModel中有一种方法可以这样做。 I have a OnExit method in the app.xaml file, but how can I access the save-method in the ViewModel from here? 我在app.xaml文件中有一个OnExit方法,但是如何从此处访问ViewModel中的保存方法?

App.xaml.cs App.xaml.cs

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

        base.OnExit(e);
    }

ViewModel.cs ViewModel.cs

    public void Save(){
        //This method save to the DB
    }

Consider using the Observer Pattern. 考虑使用观察者模式。 Register your view-models as subscribers to an App's Close event. 将您的视图模型注册为App的Close事件的订阅者。 When the app's close event is triggered, notify your subscribers (ie view-models) so that they can react to that event. 当应用程序的关闭事件被触发时,通知您的订阅者(即视图模型),以便他们可以对该事件做出反应。

  • Prism provides an EventAggregator. Prism提供一个EventAggregator。

  • Xamarin.Forms provides a MessagingCenter. Xamarin.Forms提供了一个MessagingCenter。

  • Bizmonger provides a MessageBus. Bizmonger提供了一个MessageBus。

You can use a mediator like the ones specified to manage a publisher / subscribe model without the classes knowing about each other. 您可以使用指定的中介程序来管理发布者/订阅模型,而无需使这些类彼此了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM