重新初始化 MasterPage 在 IOS - Xamarin 表单中抛出 null 异常

2024-02-10

我有一个 MDPage,它是一个 MasterDetailPage,它将侧面菜单项列表页面称为主页面。此详细信息是通过主页的新导航页面添加的。

我的代码是

public MDPage(){
Master = new SideMenuPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;

Detail = new NavigationPage(new HomePage())
{
    BarBackgroundColor = Color.Black,
    BarTextColor = Color.White,
};}

我有一个要求,导航页面包含底部菜单,这样在单击底部菜单时,需要重新初始化 MDPage 以设置不同页面(例如“关于我们”页面)的新导航页面。所以我为 MDPage 添加了一个参数化构造函数,然后单击我正在调用的底部菜单项App.Current.MainPage = new MDPage("AboutUs").下面是参数化构造函数。

  public MDPage(string bottomMenuItem)
 {
Master = new SideMenuPage();
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;

if("AboutUs" == bottomMenuItem)
{
   Detail = new NavigationPage(new AboutUs())
   {
      BarBackgroundColor = Color.Black,
      BarTextColor = Color.White,
   };
}}

当我打开应用程序时,首先调用 MDPage 构造函数。然后,从侧面菜单中,我可以选择打开作为详细信息添加的主页。请注意,此主页包含一个底部子菜单,它只是一个图像。点击此按钮后,它应该再次重新初始化 MDPage。这在 Andorid 中运行良好。但在 iOS 中,它会抛出 null 异常。它不允许我设置Master = new SideMenuPage();我通过反复试验找到了根本原因,因为此代码不会抛出异常,而是在 iOS Main.cs 文件中抛出。请帮我。

主页 - XAML

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:ClubApp.Views;assembly=ClubApp"
             x:Class="ClubApp.Views.MainPage">

  <MasterDetailPage.Master>
    <local:MasterPage x:Name="masterPage" />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>

      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

MainPage.xaml.cs

using System.Linq;using System.Text;using System.Threading.Tasks;using Xamarin.Forms;namespace Test.Views{
public partial class MainPage : MasterDetailPage
{
    public MainPage()
    {

        Master = new MasterPage();
        InitializeComponent();
        masterPage.ListView.ItemSelected += OnItemSelected;

        Detail = new NavigationPage(new Views.HomePage())
        {
            BarBackgroundColor = Color.Black,
            BarTextColor = Color.White,
        };
    }

    public MainPage(string bottomMenu)
    {

        Master = new MasterPage();
        InitializeComponent();
        masterPage.ListView.ItemSelected += OnItemSelected;

        if ("News" == bottomMenu)
        {
            Detail = new NavigationPage(new Views.HomePage())
            {
                BarBackgroundColor = Color.Black,
                BarTextColor = Color.White,
            };
        }
        else if ("Profile" == bottomMenu)
        {

            Detail = new NavigationPage(new Views.Profile())
            {
                BarBackgroundColor = Color.Black,
                BarTextColor = Color.White,
            };
        }
    }

    async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        try
        {
            var item = e.SelectedItem as MasterPageItem;
            if (item != null)
            {
                if (item.Title == "News")
                {
                    Detail = new NavigationPage(new Views.NewsPage())
                    {
                        BarBackgroundColor = Color.Black,
                        BarTextColor = Color.White,
                    };
                }

                if (item.Title == "Home")
                {

                    Detail = new NavigationPage(new Views.HomePage())
                    {
                        BarBackgroundColor = Color.Black,
                        BarTextColor = Color.White,
                    };
                }
                if (item.Title == "Profile")
                {

                    Detail = new NavigationPage(new Views.Profile())
                    {
                        BarBackgroundColor = Color.Black,
                        BarTextColor = Color.White,
                    };
                }

                masterPage.ListView.SelectedItem = null;
                IsPresented = false;
            }
        }
        catch (Exception ex)
        {

        }

    }
}}

母版页.xaml

<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             x:Class="Test.Views.MasterPage">  <ContentPage.Content>
<StackLayout   VerticalOptions="FillAndExpand" BackgroundColor="#10000c" Padding = "0,50,0,0" >
  <StackLayout  x:Name="slUserProfile" Orientation="Vertical" Spacing = "0" 
                VerticalOptions="FillAndExpand">
    <Image Source="{Binding member_image}" x:Name="imgSideImage"
             HorizontalOptions="CenterAndExpand" Aspect="AspectFill" HeightRequest="100" 
             WidthRequest="100" />

    <Label Text="{Binding name}" TextColor="#efa747" 
                          FontSize ="17"
                          HorizontalOptions="CenterAndExpand"/>
  </StackLayout >

  <ListView x:Name="lvSideMenu" VerticalOptions="FillAndExpand" SeparatorVisibility="None" 
            BackgroundColor="Black">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <StackLayout Padding="15,5,0,0" Orientation="Horizontal">
            <Image Source="{Binding IconSource}"/>
            <StackLayout Padding = "10,0,0,0">
              <local:CustomLabel Text="{Binding Title}" VerticalOptions="CenterAndExpand"
                   TextColor="#dac6ac" FontSize ="14"/>
            </StackLayout>
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout></ContentPage.Content></ContentPage>

MasterPage.xaml.cs

using Xamarin.Forms;namespace Test.Views{
public partial class MasterPage : ContentPage
{
    public ListView ListView { get { return lvSideMenu; } }
    public Page Detail { get; set; }
    public MasterPage()
    {
        InitializeComponent();
        var masterPageItems = new List<MasterPageItem>();  
        //Fills side menu items.
        masterPageItems.Add(new MasterPageItem
        {
            Title = "Profile",
            IconSource = "profile_sidemenu.png"
        });
        masterPageItems.Add(new MasterPageItem
        {
            Title = "Home",
            IconSource = "home_smenu.png"
        });
        masterPageItems.Add(new MasterPageItem
        {
            Title = "News",
            IconSource = "news_smenu.png"
        });
        lvSideMenu.ItemsSource = masterPageItems;
        Icon = "menu.png";
        Title = "Menu";   
    }
}
public class MenuItems
{
    public string MenuTitle { get; set; }
}
public class MasterPageItem
{
    public string Title { get; set; }
    public string IconSource { get; set; }
}}

主页.xaml

<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"           x:Class="Test.Views.HomePage" Title="Home"><ContentPage.Content><StackLayout>   <Label Text="This is Home page"/></StackLayout></ContentPage.Content></ContentPage>

配置文件.xaml

<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Test.Views.Profile" Title="Profile"><ContentPage.Content>   <StackLayout>
    <StackLayout>
      <Label Text="This is Profile page" />
    </StackLayout>
    <StackLayout HeightRequest="80">
      <Grid RowSpacing="0" ColumnSpacing="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <StackLayout x:Name="tProfile" BackgroundColor="Red" Grid.Column="0" Spacing="0" Padding="0,10,0,10">
          <Image Source="bprofileSel.png" HorizontalOptions="Center" VerticalOptions="End"/>
          <Label Text="Profile" FontSize="10" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"/>
        </StackLayout>
        <StackLayout x:Name="tNews" BackgroundColor="Black" Grid.Column="1" Spacing="0" Padding="0,10,0,10">
          <Image Source="bNewsUnsel.png" HorizontalOptions="Center" VerticalOptions="End"/>
          <local:CustomLabel Text="News" FontSize="10" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"/>
        </StackLayout>
      </Grid>
    </StackLayout>
 </StackLayout></ContentPage.Content></ContentPage>

配置文件.xaml.cs

Using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Xamarin.Forms;namespace Test.Views{
public partial class Profile : ContentPage
{

    public Profile()
    {

        InitializeComponent();
        try
        {
            tProfile.GestureRecognizers.Add(new TapGestureRecognizer
            {
                Command = new Command(() => ProfileClicked()),
            });

            tNews.GestureRecognizers.Add(new TapGestureRecognizer
            {
                Command = new Command(() => NewsClicked()),
            });
        }
        catch (Exception ex)
        {
        }
    }

    private void ProfileClicked()
    {
        App.Current.MainPage = new MainPage("Profile");
    }

    private void NewsClicked()
    {
        App.Current.MainPage = new MainPage("News");
    }
}}

新闻页面可以像个人资料页面一样设置。在 app.cs 中调用 MainPage = new MainPage()

当应用程序启动时,它将显示带有侧面菜单的主页。现在,当我单击菜单(例如侧面菜单中的个人资料)时,它将带我进入个人资料页面,根据设计,可以在那里看到底部子菜单。点击它会导致iOS代码中出现null异常。这在安卓上运行良好。我的假设是根本原因是由于 MasterPage 重新初始化为 Master。但我需要像这样飞行的要求。请帮我。

This is the error in iOS Main.cs iOS Error


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重新初始化 MasterPage 在 IOS - Xamarin 表单中抛出 null 异常 的相关文章

随机推荐

  • 读取接收和发送的网络流量字节

    在 Objective C 中获取网络流量发送和接收字节的最简单方法是什么 这并不容易 而且它来自 C 而不是 Objective C 但是您需要的所有信息都存储在返回给您的接口地址的 ifa data 字段中获取ifaddrs 3 您可以
  • Google 地图 API 密钥警报

    我的 Google 地图 API 密钥有问题 我收到一条警报说 This web site needs a different Google Maps API key 当我按 确定 收到警报时 地图正在加载并且工作正常 同样的问题已经发布
  • 如何向 Python shell 添加制表符补全?

    当使用启动 django 应用程序时python manage py shell 我得到一个 InteractiveConsole shell 我可以使用制表符完成等 Python 2 5 1 r251 54863 Apr 15 2008
  • Rails image_tag 旋转图像

    我使用亚马逊的 S3 进行图像存储 并配置了载波和雾 图像似乎存储正确 但是当我有 肖像 图像 宽度小于高度 时 它无法正确显示 而是将图像旋转到其一侧 任何正确方向的指示将不胜感激 上传者 image uploader rb class
  • C/C++ 处理程序 SIGFPE 是什么?

    好吧 我搜索了有关 SIGFPE 的文章 然后我写了一些测试 但它的行为很奇怪 那我只好在这里发帖寻求帮助了 GCC G 或 ISO C 是否明确定义了除以零会发生什么 1 我搜索了这篇文章 除以零不会抛出 SIGFPE https sta
  • 在 swift 3 中以编程方式设置 UIImageView AspectRatio 约束

    我在故事板中有一个 UIImageView 其 AspectRatio 为 1 1 在某些情况下我想在 ViewController 中以编程方式更改为 2 1 我在 ViewController 中创建该约束的引用 但无法设置该约束 您可
  • 使用引导工具提示进行 Javascript 验证

    当验证返回 false 时 我在启动输入字段的引导工具提示时遇到问题 更多细节 我有想法用 javascript 函数验证我的表单 这工作得很好 但是当验证错误时一定会发生一些事情 我正在考虑引导工具提示 简单 易于控制 现在对我来说是最好
  • Django ModelChoiceField 允许创建对象

    姜戈的ModelChoiceField https docs djangoproject com en 1 8 ref forms fields django forms ModelChoiceField是从模型派生表单时用于外键的默认表单
  • 当使用 unicorn 启动 Rails 时,Nginx 失败(13:权限被拒绝)

    我的 Rails 应用程序在服务器上运行Unicorn and Nginx 但是在配置Nginx并启动它之后 我收到错误 2015 08 03 15 43 44 crit 13951 0 1 stat home ec2 user apps
  • 使用 Python 从 Google Drive / Workspace 下载电子表格

    您能否生成一个 Python 示例 说明如何下载给定密钥和工作表 ID 的 Google Sheets 电子表格 gid 我不能 我已经搜索了 API 的版本 1 2 和 3 我运气不好 我无法弄清楚他们复杂的类似 ATOM 的 feed
  • 根据 pandas DataFrame 中的值序列生成索引元组

    这是我之前问题的后续 根据 pandas DataFrame 列中的值序列查找行索引 https stackoverflow com questions 61735585 finding the index of rows based on
  • 将对象插入哈希表 (C++)

    这是我第一次制作哈希表 我试图将字符串 键 与指向 Strain 类对象 数据 的指针相关联 Simulation h include
  • 细粒度的权限;主要权限——角色与权限分离;

    我在 wcf 服务中使用 PrimaryPermission 一段时间了 PrincipalPermission SecurityAction Demand 角色 SecurityRoles CanManageUsers 我们的角色前缀为
  • 如何知道我使用的是哪个 Android 支持库 v4 修订版?

    我可以在 Android SDK 管理器中看到我的计算机上安装的版本 在 Android SDK 管理器中 但通常项目使用 libs 文件夹中自己的副本 除了文件日期之外 有什么方法可以告诉我在特定项目中使用的是 android suppo
  • IntelliJ - 调试设置下一条语句?

    在 IntelliJ 中调试时如何退回到上一行 我在调试菜单或命令中没有看到任何执行此操作的内容 目前 IDEA 不支持向后调试 不过 对于 Java 调试器工具栏上有 Drop Frame 操作和按钮 它可以让您在堆栈中向上移动一帧并重新
  • 为 Objective-C 集合实现 -hash / -isEqual: / -isEqualTo...:

    Note 以下问题是相关的 但它们和链接的资源似乎都没有完全回答我的问题 特别是与实施平等测试有关对象的集合 覆盖 isEqual 和 hash 的最佳实践 https stackoverflow com questions 254281
  • 分析 iOS 中的 Assets.car 文件

    我试图减少 iOS 应用程序的整体大小 目前为 48MB 当我分析子文件夹时 我发现 Assets car 占用了 41MB 我无法打开并查看哪个占用了那么多空间 我找不到有关 Assets car 文件的任何好的文档 有人可以建议如何查看
  • 为什么 C++ 在将 float 转换为 char 时不显示缩小转换错误?

    使用编译此代码g std c 17 Wall pedantic main cpp不会产生任何警告 include
  • 如何将 JSON 字符串转换为 JavaScript 中的函数?

    如何将 javascript jquery 中的字符串转换为函数 我正在尝试使用 JSON 参数列表来初始化函数 但是 其中一个参数是一个函数 我将其存储为字符串 当我尝试使用 eval 返回该函数时 出现错误 例如 如果我的 JSON 是
  • 重新初始化 MasterPage 在 IOS - Xamarin 表单中抛出 null 异常

    我有一个 MDPage 它是一个 MasterDetailPage 它将侧面菜单项列表页面称为主页面 此详细信息是通过主页的新导航页面添加的 我的代码是 public MDPage Master new SideMenuPage Initi