如何使用ViewModel在我的应用程序中进行交流? [英] How can I communicate in my app with 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 ContentPage
as 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屋!