Xamarin.Forms:PageRenderer中的NavigationController为null

时间:2018-05-03 07:13:45

标签: c# xamarin.forms xamarin.ios custom-renderer

我正在尝试使用PageRenderer来自定义/重新定位iOS ToolbarItem的元素,但此处NavigationController会抛出空引用异常。 在我的代码下面

   public class MyNavigationRenderer: PageRenderer
    {    
        public new MyNavigationBar Element
        {
            get { return (MyNavigationBar)base.Element; }
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            var LeftNavList = new List<UIBarButtonItem>();
            var rightNavList = new List<UIBarButtonItem>();
            var navigationItem = this.NavigationController.TopViewController.NavigationItem;

            for (var i = 0; i < Element.ToolbarItems.Count; i++)
            {
                var reorder = (Element.ToolbarItems.Count - 1);
                var ItemPriority = Element.ToolbarItems[reorder - i].Priority;

                if (ItemPriority == 1)
                {
                   UIBarButtonItem LeftNavItems = navigationItem.RightBarButtonItems[i];
                   LeftNavList.Add(LeftNavItems);
                }
                else if (ItemPriority == 0)
                {
                   UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
                   rightNavList.Add(RightNavItems);
                }
            }
             navigationItem.SetLeftBarButtonItems(LeftNavList.ToArray(), false);
             navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
        }
    }

便携式/共享表单项目中的MyNavigationBar.cs

public class MyNavigationBar : NavigationPage
{
    public MyNavigationBar(Page content) : base(content)
    {
        Init();
    }
    private void Init()
    {
        this.ToolbarItems.Add(new ToolbarItem() { Icon = "kid", Priority = 0, Order = ToolbarItemOrder.Primary });
        this.ToolbarItems.Add(new ToolbarItem() { Text = "License", Priority = 0, Order = ToolbarItemOrder.Primary });
    }    
} 

应用程序启动

public App ()
{
    InitializeComponent();
    MainPage = new MyNavigationBar(new LoginPage());
} 

见下面的截图获取异常

enter image description here

1 个答案:

答案 0 :(得分:0)

我遇到了这个问题,但在我的情况下,我试图从没有NavigationController的内容页面获取NavigationController,确保在调用TopViewController之前进行null检查,

    date_axis = TimeAxisItem(self.xdict, orientation='bottom')
    self.plot1 = pg.PlotWidget(axisItems = {'bottom': date_axis})
    self.plot1.setXRange(-1, 50)
    self.plot1.setLimits(xMin=-100, xMax=1100)

    item = CandlestickItem(data)    #plot candel stick
    self.plot1.addItem(item)

    date_axis = TimeAxisItem(self.xdict, orientation='bottom')
    self.plot2 = pg.PlotWidget(axisItems = {'bottom': date_axis})
    self.plot2.setXRange(-1, 50)
    self.plot2.setLimits(xMin=-100, xMax=1100)

    self.plot2.plot(list(self.xdict.keys()), y)

例如, 当用户打开应用程序时,他将看到“登录”页面,该页面没有任何导航栏。