页间通信

时间:2017-01-26 15:51:10

标签: ios xamarin mvvm mvvmcross

在我的iOS项目中,我有三页A,B,C

该应用导航自A - > B - > C.

如果这些页面已订阅该活动但尚未显示,我是否可以在A页面上发布将在B和C页面上收到的活动?

1 个答案:

答案 0 :(得分:0)

如果您在A,B和C尚未显示,则他们无法对任何事件进行有效订阅。因此,他们不会收到这些事件。

如果你想让它在Android上工作,你也不能依赖这种模式。

相反,我会考虑使用一个服务,这是一个简单的可解析单例,你可以存储东西,让ViewModel在ctor中注入该服务。

这样的事情:

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

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

然后在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; }
}

View Bodel for View B:

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

或者,如果您只传递较小的值(例如Id),则可以使用请求参数:

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

然后在您的VM中:

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