首页 > 解决方案 > Xamarin.Forms:处理导航工具栏按钮(Shell)

问题描述

我想处理我的 Xamarin.Forms 应用程序(android 版本)中的任何后退点击。

对于 Android/硬件按钮非常简单,我所要做的就是重写 OnBackButtonPressed 方法。但是这个顶部工具栏并不那么容易。我听说它应该与 Shell.SetBackButtonBehavior 一起使用,但由于某种原因,它对我不起作用。

我的代码是这样的,在InitializeComponents()之后放在页面构造函数中。

Shell.SetBackButtonBehavior(this, new BackButtonBehavior {
            Command = new Command(async () =>
                await Shell.Current.DisplayAlert("Back","Back","Back")
            )
        });

知道有什么问题吗?

标签: c#.netxamlxamarinxamarin.forms

解决方案


该功能可以通过在xaml中定义Shell.BackButtonBehavior,在cs中实现Command来实现。

这是我的一个小例子:

在xml中:</p>

<Shell.BackButtonBehavior>
    <BackButtonBehavior Command="{Binding GoBack}" >
    </BackButtonBehavior>
</Shell.BackButtonBehavior>
<ContentPage.Content>
    <StackLayout>
        <Label Text="Welcome to Xamarin.Forms!"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>

在 cs 中:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
    public ICommand GoBack { get; set; }
    public Page2()
    {
        InitializeComponent();
        GoBack = new Command(async () =>
            await Shell.Current.DisplayAlert("Back", "Back", "Back"));
        BindingContext = this;
    }
    
}

推荐阅读