如何解决如何重写后退按钮的操作
定向到页面 BApp.Current.MainPage.Navigation.PushAsync(new B_Page())
后退按钮的动作(在页面的左上角)的原始行为是返回到最后一页(Page-A)。 -->Action_A
现在,我想通过按后退按钮来重写将页面更改为新页面(称为页面-C)的行为。 -->Action_B
使用Xamarin.Forms.Application.Current.MainPage = new NavigationPage(new C_Page());
但我想保留这两种行为,因为我会在不同的场景中使用它们。
如何保留这两种行为以及如何让我指定要使用的操作?
让我在场景 A 中使用 Action_A,在场景 B 中使用 Action_B。
感谢您的热情回复。
解决方法
您可以使用此覆盖方法来管理上述场景
`
protected override bool OnBackButtonPressed()
{
//here you can manage your Navigation.
return base.OnBackButtonPressed();
}
`
,我们可以重新编写 ContentPage 的 Navigation View 。并根据需要重新编写后退按钮。
创建一个 BaseContentPage
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace xxx
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class BaseContentPage: ContentPage
{
public event EventHandler BackButtonAction;
public BaseContentPage()
{
InitializeComponent();
NavigationPage.SetHasBackButton(this,false);
TitleLab.Text = Title;
}
private void Button_Clicked(object sender,EventArgs e)
{
this.BackButtonAction(sender,e);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="xxx.BaseContentPage">
<NavigationPage.TitleView>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*" />
<ColumnDefinition Width="0.6*" />
<ColumnDefinition Width="0.2*" />
</Grid.ColumnDefinitions>
<!--you could set the icon or image here as back button-->
<Button BackgroundColor="Transparent" TextColor="White" Grid.Column="0" Text="Back" Clicked="Button_Clicked" />
<Label x:Name="TitleLab" Grid.Column="1" TextColor="White" FontSize="18" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Grid>
</NavigationPage.TitleView>
</ContentPage>
而您只需要创建 BaseContentPage
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App11
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PageA : Page1
{
public PageA()
{
InitializeComponent();
this.BackButtonAction += PageA_BackButtonAction;
}
private void PageA_BackButtonAction(object sender,EventArgs e)
{
//do something you want
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<local:Page1 xmlns:local="clr-namespace:App11" xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App11.PageA">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</local:Page1>
您可以根据需要在不同的场景中处理不同的导航逻辑。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。