如何使用ViewModel在我的应用程序中进行交流? [英] How can I communicate in my app with ViewModel?

查看:100
本文介绍了如何使用ViewModel在我的应用程序中进行交流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的应用程序中与ViewModel通信?

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

在我的ViewModel中,我订阅了该消息,但是它不起作用.我的消息永远不会显示.

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

推荐答案

您应该使用 ContentPage 中的MyViewModel,然后 MessagingCenter Subscribe可以使用.

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

但是,我发现这不适用于iOS设备,但适用于Android.

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

这是解决此问题的解决方法,您可以在初始化时将ContentPage作为 ViewModel 的属性传递.

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

ContentPage 中,进行如下修改:

public MainPage()
{
    InitializeComponent();

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

iOS效果:

Android效果:

Android effect :

这篇关于如何使用ViewModel在我的应用程序中进行交流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆