Xamarin.forms 如何处理xamarin iOS/Android中的导航返回按钮事件?

Xamarin.forms 如何处理xamarin iOS/Android中的导航返回按钮事件?,xamarin.forms,xamarin.ios,xamarin.android,navigation,back-button,Xamarin.forms,Xamarin.ios,Xamarin.android,Navigation,Back Button,我正在创建xamarin表单应用程序,我想在导航返回按钮上执行一些操作。有什么方法可以做到这一点吗 注意:>软件后退按钮,而不是硬件后退按钮。在中,您将找到所有内容 如果文章在某个时候消失或更改,您将在这里找到解决方案的细节 您需要创建一个自定义内容页 namespace WhateverYourNamespace { public class CoolContentPage : ContentPage { /// <summ

我正在创建xamarin表单应用程序,我想在导航返回按钮上执行一些操作。有什么方法可以做到这一点吗

注意:>软件后退按钮,而不是硬件后退按钮。

在中,您将找到所有内容

如果文章在某个时候消失或更改,您将在这里找到解决方案的细节

您需要创建一个自定义内容页

namespace WhateverYourNamespace
    {
        public class CoolContentPage : ContentPage
        {
            /// <summary>
            /// Gets or Sets the Back button click overriden custom action
            /// </summary>
            public Action CustomBackButtonAction { get; set; }

            public static readonly BindableProperty EnableBackButtonOverrideProperty =
                   BindableProperty.Create(
                   nameof(EnableBackButtonOverride),
                   typeof(bool),
                   typeof(CoolContentPage),
                   false);

            /// <summary>
            /// Gets or Sets Custom Back button overriding state
            /// </summary>
            public bool EnableBackButtonOverride
            {
                get
                {
                    return (bool)GetValue(EnableBackButtonOverrideProperty);
                }
                set
                {
                    SetValue(EnableBackButtonOverrideProperty, value);
                }
            }
        }
    }
iOS: iOS您需要覆盖CoolContentPageRenderer类中的viewWillAspect()方法

public override void ViewWillAppear(bool animated)
{
     base.ViewWillAppear(animated);

     if (((CoolContentPage)Element).EnableBackButtonOverride)
     {
          SetCustomBackButton();
     }
}

private void SetCustomBackButton()
{
     // Load the Back arrow Image
     var backBtnImage = 
     UIImage.FromBundle("iosbackarrow.png");

     backBtnImage = 
     backBtnImage.ImageWithRenderingMode
     (UIImageRenderingMode.AlwaysTemplate);

     // Create our Button and set Edge 
     // Insets for Title and Image
     var backBtn = new UIButton(UIButtonType.Custom)
     {
          HorizontalAlignment =   
          UIControlContentHorizontalAlignment.Left,
          TitleEdgeInsets = 
          new UIEdgeInsets(11.5f, 15f, 10f, 0f),
          ImageEdgeInsets = 
          new UIEdgeInsets(1f, 8f, 0f, 0f)
     };

     // Set the styling for Title
     // You could set any Text as you wish here
     backBtn.SetTitle("Back", UIControlState.Normal);
     // use the white color in ios back button text
     backBtn.SetTitleColor(UIColor.White,
     UIControlState.Normal); 
     backBtn.SetTitleColor(UIColor.LightGray, 
     UIControlState.Highlighted);
     backBtn.Font = UIFont.FromName("HelveticaNeue",
     (nfloat)17);

     // Set the Image to the button
     backBtn.SetImage(backBtnImage, UIControlState.Normal);

     // Allow the button to Size itself
     backBtn.SizeToFit();

     // Add the Custom Click event you would like to 
     // execute upon the Back button click
     backBtn.TouchDown += (sender, e) =>
     {
          // Whatever your custom back button click handling
          if(((CoolContentPage)Element)?.
          CustomBackButtonAction != null)
          {    
            ((CoolContentPage)Element)?.
               CustomBackButtonAction.Invoke();
          }
     };

     //Set the frame of the button
     backBtn.Frame = new CGRect(
          0,
          0,
          UIScreen.MainScreen.Bounds.Width / 4,
          NavigationController.NavigationBar.Frame.Height);

     // Add our button to a container
     var btnContainer = new UIView(
     new CGRect(0, 0, 
     backBtn.Frame.Width, backBtn.Frame.Height));
     btnContainer.AddSubview(backBtn);

     // A dummy button item to push our custom  back button to
     // the edge of screen (sort of a hack)
     var fixedSpace = 
     new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
     {
          Width = -16f
     };
     // wrap our custom back button with a UIBarButtonItem
     var backButtonItem = new UIBarButtonItem("",
     UIBarButtonItemStyle.Plain, null)
     {
          CustomView = backBtn
     };

     // Add it to the ViewController
     NavigationController.TopViewController.
     NavigationItem.LeftBarButtonItems 
     = new[] { fixedSpace, backButtonItem };
}
因此,下面的代码应该放在CoolContentPageRenderer类中

public override void ViewWillAppear(bool animated)
{
     base.ViewWillAppear(animated);

     if (((CoolContentPage)Element).EnableBackButtonOverride)
     {
          SetCustomBackButton();
     }
}

private void SetCustomBackButton()
{
     // Load the Back arrow Image
     var backBtnImage = 
     UIImage.FromBundle("iosbackarrow.png");

     backBtnImage = 
     backBtnImage.ImageWithRenderingMode
     (UIImageRenderingMode.AlwaysTemplate);

     // Create our Button and set Edge 
     // Insets for Title and Image
     var backBtn = new UIButton(UIButtonType.Custom)
     {
          HorizontalAlignment =   
          UIControlContentHorizontalAlignment.Left,
          TitleEdgeInsets = 
          new UIEdgeInsets(11.5f, 15f, 10f, 0f),
          ImageEdgeInsets = 
          new UIEdgeInsets(1f, 8f, 0f, 0f)
     };

     // Set the styling for Title
     // You could set any Text as you wish here
     backBtn.SetTitle("Back", UIControlState.Normal);
     // use the white color in ios back button text
     backBtn.SetTitleColor(UIColor.White,
     UIControlState.Normal); 
     backBtn.SetTitleColor(UIColor.LightGray, 
     UIControlState.Highlighted);
     backBtn.Font = UIFont.FromName("HelveticaNeue",
     (nfloat)17);

     // Set the Image to the button
     backBtn.SetImage(backBtnImage, UIControlState.Normal);

     // Allow the button to Size itself
     backBtn.SizeToFit();

     // Add the Custom Click event you would like to 
     // execute upon the Back button click
     backBtn.TouchDown += (sender, e) =>
     {
          // Whatever your custom back button click handling
          if(((CoolContentPage)Element)?.
          CustomBackButtonAction != null)
          {    
            ((CoolContentPage)Element)?.
               CustomBackButtonAction.Invoke();
          }
     };

     //Set the frame of the button
     backBtn.Frame = new CGRect(
          0,
          0,
          UIScreen.MainScreen.Bounds.Width / 4,
          NavigationController.NavigationBar.Frame.Height);

     // Add our button to a container
     var btnContainer = new UIView(
     new CGRect(0, 0, 
     backBtn.Frame.Width, backBtn.Frame.Height));
     btnContainer.AddSubview(backBtn);

     // A dummy button item to push our custom  back button to
     // the edge of screen (sort of a hack)
     var fixedSpace = 
     new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
     {
          Width = -16f
     };
     // wrap our custom back button with a UIBarButtonItem
     var backButtonItem = new UIBarButtonItem("",
     UIBarButtonItemStyle.Plain, null)
     {
          CustomView = backBtn
     };

     // Add it to the ViewController
     NavigationController.TopViewController.
     NavigationItem.LeftBarButtonItems 
     = new[] { fixedSpace, backButtonItem };
}
如何使用它

<WhateverYourNamespace:CoolContentPage 
 xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 xmlns:WhateverYourNamespace=
 "clrnamespace:XFNavBarBackBtnClickOverride;
 assembly=XFNavBarBackBtnClickOverride"
 x:Class="XFNavBarBackBtnClickOverride.Page2"             
 Title="Page 3"
 EnableBackButtonOverride="True"
 BackgroundColor="#00bfff">
  <StackLayout
    Spacing="20"
    Padding="20,10,20,10"
    VerticalOptions="Center"
    HorizontalOptions="Center" >

    <Label Text="This is the cool page, 
    which has the Navigation Bar Back button 
    click overriden. How go ahead and click that Back     
        button! ;)"
           FontSize="20"
           HorizontalTextAlignment="Center"
           TextColor="White"/>

  </StackLayout>
</WhateverYourNamespace:CoolContentPage>

对于ANDROID,在LoadApplication(new App())行之后的主活动OnCreate()中添加此项

Android.Support.V7.Widget.Toolbar
=this.findviewbyd(资源.Id.toolbarSetSupportActionBar(工具栏);

虽然此链接可能包含此问题的答案,但它可能会在某个时间点消失或更改。请在此处将此链接中的解决方案的细节添加到您的答案中。@FrqSalah我已经这样做了,但我面临着错误,我在那篇文章中也提到了我的错误。@BhautikDalicha您面临的错误是什么?请原谅请你解释一下你所说的一切question@FrqSalah在完成所有这些之后,它只截获了硬件返回按钮。iOS呢?
Android.Support.V7.Widget.Toolbar toolbar 
    = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbarSetSupportActionBar(toolbar);