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

时间:2018-11-23 08:09:17

标签: xamarin navigation custom-controls

我想为不同的页面应用一些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类,但我认为不可能。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您查看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添加一个方法,该方法将返回一种颜色,然后在渲染器内部,一旦知道要推送的页面正在实现IMyPageType1,就可以调用该方法并将颜色获取为使用。