Skip to content

Instantly share code, notes, and snippets.

@RedTahr
Last active January 27, 2016 19:22
Show Gist options
  • Save RedTahr/2dead3638ab4cb0da4b0 to your computer and use it in GitHub Desktop.
Save RedTahr/2dead3638ab4cb0da4b0 to your computer and use it in GitHub Desktop.
Xamarin.Forms BasePage
namespace ... {
// for supporting this
// public partial class "Derived"Page : "Derived"PageXaml {.... } for a xaml/cs page
// then
// <?xml version="1.0" encoding="utf-8" ?><local:"Derived"tPageXaml xmlns="ht...
// with this bit in the cs file
// public partial class "Derived"PageXaml : BasePageOverrideBackButton<ViewModel."Derived"ViewModel> { }
public class BasePageOverrideBackButton<T> : BasePage<T> where T : ViewModel.BaseViewModel, new() {
public BasePageOverrideBackButton() : base() {
}
protected override bool OnBackButtonPressed() {
base.OnBackButtonPressed();
App.GoHome();
return true;
}
}
#region BasePage with ViewModel
public class BasePage<T> : BasePage where T : ViewModel.BaseViewModel, new() {
protected T viewModel;
public BasePage() : base() {
BindingContext = ViewModel;
}
public T ViewModel {
get {
return viewModel ?? (viewModel = new T());
}
}
~BasePage() {
viewModel = null;
}
}
#endregion
public class BasePage : ContentPage {
// idea from XLabs
protected override void OnAppearing() {
base.OnAppearing();
if (BindingContext != null && BindingContext is BaseViewModel) {
var vm = (BaseViewModel)BindingContext;
vm?.OnAppearing();
// more stuff... build toolbar items...dance a jig.
}
}
protecte override void OnDisappearing() {
base.OnDisappearing();
if (BindingContext != null && BindingContext is BaseViewModel) {
var vm = (BaseViewModel)BindingContext;
vm?.OnDisappearing();
}
}
// override Androids back button, for when I'm running an app with MasterDetail and only want certain pages to exit the app.
protected override bool OnBackButtonPressed() {
base.OnBackButtonPressed();
App.GoHome(); // go to a home screen or where ever
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment