Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Arriving or Leaving a ViewModel with BuildIt.Lifecycle

Often when arriving at a page/view it’s necessary to invoke some code in order to load data, or refresh the contents on the page. Of course, this needs to happen within the ViewModel. For BuildIt.Lifecycle, this is means implementing the IArrivingViewModelState interface which defines a single method, Arriving, which will get invoked when the user arrives at the page/view (and the corresponding viewmodel).

public async Task Arriving()
    await Task.Delay(2000);
    Name += ".... arrived ....";

Note that the method returns a Task, so you can do asynchronous code in order to retrieve data.

On the Windows platform the Universal Windows Platform has methods OnNavigatedTo, OnNavigatingFrom and OnNavigatedFrom which can be overridden in the code behind of a Page. These correspond to when a user arrives, is about to leave and has left a page. The Arriving method in BuildIt.Lifecycle maps to the OnNavigatedTo method. There are two more interfaces, IAboutToLeaveViewModelState and ILeavingViewModelState, which can be used to define methods AboutToLeave and Leaving. These methods map to the OnNavigatingFrom and OnNavigatedFrom methods.

One thing to note about the AboutToLeave method is that it has a CancelEventArgs as a parameter. The code in the AboutToLeave method can set the Cancel property on this parameter to true in order to cancel the navigation away from the page (note that this maps to cancelling the state change which drives the change in pages).

public async Task AboutToLeave(CancelEventArgs cancel)
    cancel.Cancel = true;

Comments are closed