簡體   English   中英

頁面間通訊

[英]Inter page communication

在我的iOS項目中,我有三個頁面A,B,C

該應用程序從A-> B-> C導航。

如果那些頁面已經訂閱了該事件,但還沒有顯示,那么我可以在A上發布一個事件嗎?

如果您在A上,並且B和C尚未顯示,則它們不能有效訂閱任何事件。 因此,他們將不會收到事件。

另外,如果您希望此模式在Android上運行,則不能依賴此模式。

相反,我會考慮使用服務,這是一個簡單的可解決的單例,您可以在其中存儲內容,並讓ViewModels在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; }
}

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

另外,如果僅傳遞較小的值(例如Id),則可以使用請求參數:

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

然后在您的VM中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM