How can I communicate in my app with ViewModel?

女生的网名这么多〃 提交于 2020-05-09 15:47:51

问题


How communicate in my app with my ViewModel?

I have this code, sleep and resume of my app

protected override void OnSleep()
{
    MessagingCenter.Send<App, string>(this, "gotosleep", "savedata");
}

in my ViewModel I subscribe to the message, but it does not work. My message is never displayed.

public MyViewModel()
{
    MessagingCenter.Subscribe<App, string>(this, "gotosleep", async (obj, item) =>
    {
        Console.WriteLine("HERE"); 
    });
}

回答1:


You should use the MyViewModel in ContentPage , then Subscribe of MessagingCenter will work .

public MainPage()
{
    InitializeComponent();

    // Use model in Content Page 
    MyViewModel viewModel = new MyViewModel();
}

However ,I find this not works in iOS device , but works in Android .

Here is the Workaround to solve this , you can pass the ContentPageas an attribute for ViewModel when initialiation.

public MyViewModel(MainPage mainPage)
{
    MessagingCenter.Subscribe<App, string>(mainPage, "gotosleep", async (obj, item) =>
    {
        Console.WriteLine("HERE"); 
        await mainPage.DisplayAlert("Message received", "arg=" + item, "OK");
    });
}

In ContentPage , modify as follow :

public MainPage()
{
    InitializeComponent();

    // Use model in Content Page 
    MyViewModel viewModel = new MyViewModel(this);
}

iOS effect :

Android effect :



来源:https://stackoverflow.com/questions/61333329/how-can-i-communicate-in-my-app-with-viewmodel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!