Allows can intercept navigation back by user for Xamarin.Forms
https://www.nuget.org/packages/NavigationSam
Droid | iOS | UWP |
---|---|---|
UWP not support (use native method OnBackButtonPressed, see example)
// Pay attention to the inherited class!!! FormsAppCompatActivitySam
public class MainActivity : global::NavigationSam.Droid.FormsAppCompatActivitySam
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
NavigationSam.Droid.Preserver.Preserve();
Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
NavigationSam.iOS.Preserver.Preserve();
return base.FinishedLaunching(app, options);
}
}
For Xamarin.Forms entry point
public partial class App : Application
{
InitializeComponent();
MainPage = new NavigationPageSam(new MainPage());
}
For pages
public partial class SamplePage : ContentPage, INavigationPopInterceptor
{
public SamplePage()
{
InitializeComponent();
}
// Important service property
public bool IsPopRequest { get; set; }
public async Task<bool> RequestPop()
{
bool res = true;
if (CheckChanges())
res = await DisplayAlert("Warning",
"If you exit, all unsaved changes will be lost",
"Exit", "Cancel");
return res;
}
// For UWP
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(async () =>
{
bool res = await RequestPop();
if (res)
await Navigation.PopAsync();
});
return true;
}
}
Same as above. INavigationPopInterceptor can implement to ViewModel
Warning: for UWP need realization method OnBackButtonPressed for Page. For detail see Sample project
public class SampleVm : BaseViewModel, INavigationPopInterceptor
{
public SampleVm()
{
//Do something...
}
// Important service property
public bool IsPopRequest { get; set; }
public async Task<bool> RequestPop()
{
bool res = true;
if (CheckChanges())
res = await Page.DisplayAlert("Warning",
"If you exit, all unsaved changes will be lost",
"Exit", "Cancel");
return res;
}
}
MIT Licensed
If this project help you reduce time to develop, you can give me a cup of coffee :) :coffee: :pizza: