【问题标题】:Inter page communication页面间通信
【发布时间】:2017-01-26 15:51:09
【问题描述】:

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

应用程序从 A --> B --> C 导航。

如果页面 B 和 C 已订阅该事件但尚未显示,我可以在 A 上发布一个事件吗?

【问题讨论】:

    标签: ios xamarin mvvm mvvmcross


    【解决方案1】:

    如果您在 A 和 B 和 C 尚未显示,他们不能有任何活动的有效订阅。因此,他们不会收到事件。

    如果您希望它在 Android 上运行,您也不能依赖这种模式。

    相反,我会考虑使用 Service,它是一个简单的可解析单例,您可以在其中存储内容,并让 ViewModel 将该服务注入到 ctor 中。

    类似这样的:

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

    然后在视图 A 的 ViewModel 中:

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

    视图 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 });
    

    然后在你的虚拟机中:

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

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      相关资源
      最近更新 更多