Xamarin:检测在 NavigationRenderer 上推送的页面

Xamarin: detect page pushed on NavigationRenderer

我想为不同的页面应用一些 navigationBar 属性(如背景图像),我想在我的自定义 NavigationRenderer 上有一个条件。

我的想法是(在我的工作代码中)有一些条件

   public class CustomNavigationRenderer : NavigationRenderer
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        if (pagePushed is 1)
        {
            NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
            NavigationBar.ShadowImage = new UIImage();
        }

        else (ahother page){
            var img = UIImage.FromBundle("MyImage");
            NavigationBar.SetBackgroundImage(img, UIBarMetrics.Default);
        }
    }
}

这让我至少有一个条件可以应用不同的导航属性。另一种方法是有 2 Navigationrenderer class 但我认为这是不可能的。

知道怎么做吗?

如果您查看 NavigationRenderer here 的源代码,您会发现有很多方法和回调可供您利用。

我建议你可以这样做:

1) 自定义 NavigationRenderer 的代码(iOS 项目,您必须在 Android 上做类似的事情):

using System.Threading.Tasks;
using MyProject.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(NavigationPage), typeof(NavRenderer))]
namespace MyProject.iOS
{
    public class NavRenderer : NavigationRenderer
    {
        protected override async Task<bool> OnPushAsync(Page page, bool animated)
        {
            var result = await base.OnPushAsync(page, animated);

            if(result)
            {
                if (page is IMyPageType1)
                {
                    NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
                    NavigationBar.ShadowImage = new UIImage();
                }

                else if(page is IMyPageType2)
                {
                    var img = UIImage.FromBundle("MyImage");
                    NavigationBar.SetBackgroundImage(img, UIBarMetrics.Default);
                }
            }

            return result;
        }
    }
}

2) 在上述代码的基础上,需要添加两个接口。这些应该位于您的页面所在的同一项目/dll 中(所有您的 Xamarin.Forms UI):

    public interface IMyPageType1
    {
    }

    public interface IMyPageType2
    {
    }

3) 现在剩下的就是在您需要的页面上实现接口。例如:

    public partial class MyPage1 : ContentPage, IMyPageType1
    {
        //...
    }

从这里开始,无限可能!例如,您可以向 IMyPageType1 添加一个方法,该方法将 return 一种颜色,然后在您的渲染器中,一旦您知道被推送的页面正在实现 IMyPageType1,您就可以调用该方法并获取要使用的颜色。