简体   繁体   English

页面间通讯

[英]Inter page communication

In my iOS project I have three pages A, B, C 在我的iOS项目中,我有三个页面A,B,C

The app navigates from A --> B --> C. 该应用程序从A-> B-> C导航。

Can I publish an event on A which would be received on page B and C, if those pages have subscribed to that event, but are not shown yet? 如果那些页面已经订阅了该事件,但还没有显示,那么我可以在A上发布一个事件吗?

If you are on A and B and C haven't been shown yet, they can't have active subscriptions to any events. 如果您在A上,并且B和C尚未显示,则它们不能有效订阅任何事件。 Hence, they will not receive the events. 因此,他们将不会收到事件。

Also you can't rely on this pattern if you want this to work on Android for instance. 另外,如果您希望此模式在Android上运行,则不能依赖此模式。

Instead I would consider using a Service, which is a simple resolvable singleton, where you can store stuff, and let the ViewModels have that service injected in the ctor. 相反,我会考虑使用服务,这是一个简单的可解决的单例,您可以在其中存储内容,并让ViewModels在ctor中注入该服务。

Something like this: 像这样:

public interface IMyService
{
    string Data { get; set; }
}

public class MyService : IMyService
{
    public string Data { get; set; }
}

Then in your ViewModel for view A: 然后在您的ViewModel中查看A:

public class AViewModel : MvxViewModel
{
    public AViewModel(IMyService service)
    {
        GoToBCommand = new MvxCommand(() => {
            // set data before navigating
            service.Data = SomeData;
            ShowViewModel<BViewModel>();
        });
    }

    public ICommand GoToBCommand { get; }
}

ViewModel for View B: 视图B的ViewModel:

public class BViewModel : MvxViewModel
{
    private readonly IMyService _service;
    public BViewModel(IMyService service)
    {
        _service = service;
    }

    public void Init()
    {
        // read data on navigation to B
        var data = _service.Data;
    }
}

Alternatively if you are only passing small values such as an Id, you could use request parameters: 另外,如果仅传递较小的值(例如Id),则可以使用请求参数:

ShowViewModel<BViewModel>(new { id = SomeProperty });

Then in your VM: 然后在您的VM中:

public void Init(string id)
{
    // do stuff with id
}

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

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