Die vorgeschlagene Lösung kann gut funktionieren, aber ich mag keine "statische Eigenschaftsexposition", um Probleme zu lösen. Darüber hinaus mag ich die Verwendung von "Eigenschaften als Methoden" -Lösungen nicht, besonders wenn viel Logik involviert ist.
Das Hauptproblem hier, wie wir die OnBackButton() Methode aus unserer Xamarin.Forms.Application-Klasse behandeln können.
Wie wäre es, das Gleiche eleganter zu machen?
Zuerst müssen Sie die Xamarin.Forms erweitern.Anwendungsklasse wie folgt aus:
namespace YourNameSpace
{
public class Application : Xamarin.Forms.Application
{
#region Public Methods
public bool HandleBackButton()
{
return OnBackPressed();
}
#endregion
#region Application Methods
protected virtual bool OnBackPressed()
{
return false;
}
#endregion
}
}
Ihre App Implementierung wird nun diese Klasse als Basisklasse verwenden. Denken Sie daran, Ihre XAML und Ihre xaml.cs entsprechend zu ändern:
<common:Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:common="clr-namespace:YourNameSpace"
x:Class="YourNameSpace.App">
</common:Application>
In Ihrer App.cs Implementierung Sie jetzt die OnBackButton() -Methode außer Kraft setzen kann.
public partial class App : YourNameSpace.Application
{
#region Constructors
public App()
{
InitializeComponent();
}
#endregion
#region App Methods
protected override bool OnBackPressed()
{
// Handle when the back button is pressed
return false;
}
#endregion
}
Dann müssen Sie ein wenig Ihre Implementierung der Aktivitätsklasse ändern.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
#region Constants and Fields
private App _app;
#endregion
#region Activity Methods
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
_app = new App();
LoadApplication(_app);
}
public override void OnBackPressed()
{
if(!_app.HandleBackButton())
base.OnBackPressed();
}
#endregion
}
Das wird nicht funktionieren, weil ich bin mit Formen Xamarin, so dass ich eine einzige Aktivität haben – Chris