Fabian Tuender
Fabian Tuender

Reputation: 35

Refresh viewmodel in app OnResume

I have an Xamarin Forms app that has some pages and related viewmodels behind it. On the pages in OnAppearing it sets the binding context to the view model. The view model calls a web api to retrieve the data. When the app goes to sleep and is called again I use the OnResume event in the App class and messagecenter to send a message. In the OnAppearing of the page I subscribe to the message and set the binding context to a new viewmodel. In the OnDisapearing I unsubscribe from the message to prevent it from receiving event when the page is not visible (another page is visible).

Is there no way to call a methods from the page it’s connected binding context? Or is it only possible to refresh the information by setting the page it’s binding context again?

Upvotes: 1

Views: 3212

Answers (1)

EvZ
EvZ

Reputation: 12179

Setting the BindingContext in the OnAppearing event will reassign the ViewModel each time you navigate to or back to your Page (depends on the platform). Usually you set the ViewModel once and in the constructor.

Regarding the MessagingCenter. Before the OnPause there will be a OnDisappearing event. So, you will unsubscribe from the message and most probably will not receive anymore after OnResume.

Beside this, there are platform specific behaviours related to OnAppearing and OnDisappearing. Luckily the documentation is covering the exception cases as well.

I am not sure I fully understand your question, but, you can call a method from a BindingContext on the Page the next way:

public partial class MyPage : Page
{
    public MyPage()
    {
        this.BindingContext = new MyViewModel();
    }

    protected override void OnAppearing()
    {
        (this.BindingContext as MyViewModel)?.MyMethod();
    }
}

Upvotes: 1

Related Questions