scriptBoris / NavigationSam

Can intercept action navigation back by user
17 stars 1 forks source link

NavigationSam

Allows can intercept navigation back by user for Xamarin.Forms

Nuget Installation

https://www.nuget.org/packages/NavigationSam

Droid iOS UWP

Supported Platforms

Install iOS project

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);
     }
}

Example

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;
     }
}

Example MVVM

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;
     }
}

License

MIT Licensed

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :) :coffee: :pizza:

paypal