I had almost the same requirement a couple of weeks ago. I wanted to make sure that event subscriptions in my view models would be unsubscribed when the page was closed. After many studies, my conclusion was that the easiest solution was to use the ContentPage.OnDisappearing method.
, , , ViewModel, , , ViewModel , . , OnAppearing OnDisappearing ( , , , , IPropertyNotify - ).
public class ViewModelBase
{
public virtual void OnAppearing()
{
}
public virtual void OnDisappearing()
{
}
}
ContentPage OnAppearing OnDisappearing, .
public class PageBase : ContentPage
{
protected override void OnDisappearing()
{
base.OnDisappearing();
var viewModel = BindingContext as ViewModelBase;
viewModel?.OnDisappearing();
}
protected override void OnAppearing()
{
var viewModel = BindingContext as ViewModelBase;
viewModel?.OnAppearing();
}
}
, , , PageBase:
<?xml version="1.0" encoding="utf-8" ?>
<pages:PageBase xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:Forms.App.Controls;assembly=Forms.App"
xmlns:converters="clr-namespace:Forms.App.Converters;assembly=Forms.App"
xmlns:pages="clr-namespace:Forms.App.Pages;assembly=Forms.App"
x:Class="Forms.App.Pages.LogonPage"
NavigationPage.HasNavigationBar="False"
Title="Logon">
ViewModel OnDisappearing :
public class FormViewModel : ViewModelBase
{
public override void OnDisappearing()
{
base.OnDisappearing();
}
}
, - , OnDisappearing , ( ). , , , . , - , . , OnAppearing OnDisappearing.
, !