【问题标题】:Xamarin.Forms: Handle Navigation toolbar button (Shell)Xamarin.Forms:处理导航工具栏按钮(Shell)
【发布时间】:2021-11-26 11:03:21
【问题描述】:

我想在我的 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# .net xaml xamarin xamarin.forms


    【解决方案1】:

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

    这是我的一个小例子:

    在xml中:

    <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;
        }
        
    }
    

    【讨论】:

    • 我确实复制了您的代码,但它不起作用。我像你一样尝试过(Xaml + xaml.cs)以及 viewModel(Xaml + VM)。但我就是不能让它工作..
    • 确保该页面不在shell中。
    • 呃,“在外壳内”是什么意思?
    • 当前页面不在Shell的“ShellContent”中。
    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2022-01-17
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多