Skip to content
This repository was archived by the owner on Aug 27, 2020. It is now read-only.

IViewModelNavigationInit

Mark Smith edited this page Jun 4, 2018 · 4 revisions

IViewModelNavigationInit

The IViewModelNavigationInit interface is used to provide an method-based initialization when a view model is about to be used by a Page. This interface should be implemented by the view model and is invoked by the FormsNavigationPageService when the NavigateAsync and PushModalAsync methods are utilized. This interface is already implemented in the SimpleViewModel implementation - you can override the IntializeAsync method.

Note: The navigation service will call this implementation (if present) on whatever view model is used by the Page. This can be the state parameter passed in (which is assigned as the view model), or it can be a view model created by the Page and associated to the BindingContext in the constructor of the Page.

It has a single method: InitializeAsync which takes the following form:

Task IntializeAsync(object stateParameter);
  • stateParameter: passed object to the NavigateAsync or PushModalAsync. Will be null if the state object was used as the view model (e.g. no BindingContext was assigned by the Page during construction.

This method is called before the Page is navigated to, and after the ViewModel has been assigned as the BindingContext for the Page. It allows for asynchronous initialization and will be awaited prior to performing the navigation.

Example

Here is an example view model that implements the interface - in this case we rely on the override from SimpleViewModel, but you can use any base class and just implement the interface directly if you prefer.

public class MyViewModel : SimpleViewModel
{
   int data;
   public MyViewModel()
   {
      data = 0;  // called first.
   }

   protected override Task IntializeAsync(object stateParameter)
   {
      data = 1; // called second. JUST BEFORE navigation.
      return base.InitializeAsync(stateParameter);
   }
}