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