我使用 Xamarin.Forms 为我的网站制作了一个简单的 WebView 应用程序,但是当我按下后退按钮时,它正在关闭该应用程序,但我希望它将我重定向到上一页(如果有(。
所以这是我到目前为止的代码:
应用xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MyApp
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace MyApp
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(true)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
Broswer.Source = "https://mywebsite.com/";
}
}
}
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyApp"
x:Class="MyApp.MainPage">
<WebView x:Name="Broswer" HeightRequest="1920" WidthRequest="1080"/>
</ContentPage>
那么如何更改我的代码以便访问硬件后退按钮?
可以覆盖OnBackButtonPressed
方法,判断网页视图是否有上一页:
protected override bool OnBackButtonPressed()
{
if (Broswer.CanGoBack)
{
Broswer.GoBack();
return true;
}
return false;
}