You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms添加AppShell时InitializeComponent缺失的解决咨询

在现有Xamarin.Forms项目中添加AppShell的完整解决方案

一、解决AppShell.xaml.cs缺少InitializeComponent()的问题

InitializeComponent()是XAML编译时自动生成的方法,不用手动编写,只要确保以下几点就能自动生成:

  1. 检查AppShell.xaml的根元素:必须包含x:Class属性,指定和代码文件一致的命名空间类名,比如:
<Shell xmlns:xaml="http://xamarin.com/schemas/2014/forms/design" 
       xmlns="http://xamarin.com/schemas/2014/forms" 
       xmlns:view="clr-namespace:İdaServis.View"
       xmlns:local="clr-namespace:İdaServis" <!-- 补充local命名空间 -->
       x:Class="İdaServis.AppShell" <!-- 必须添加这个属性 -->
       FlyoutWidth="400"
       FlyoutHeight="200">
  1. 检查AppShell.xaml.cs的结构:代码文件要正确继承Shell,并保持命名空间和x:Class一致:
namespace İdaServis
{
    public partial class AppShell : Shell
    {
        public AppShell()
        {
            InitializeComponent(); // 配置正确后会自动生成
        }
    }
}
  1. 重新生成项目:右键项目→清理解决方案,再重新生成,IDE会自动在obj文件夹下生成包含InitializeComponent()的.g.cs文件。

二、无需新建项目,分步集成AppShell到现有项目

1. 修改应用启动逻辑

打开App.xaml.cs,把原来设置MainPage的代码替换为启动AppShell:

public App()
{
    InitializeComponent();
    // 替换原来的MainPage设置,比如删除NavigationPage相关代码
    MainPage = new AppShell();
}

2. 修复你的AppShell.xaml代码问题

你的代码里缺少local命名空间声明,导致local:AboutPage这类引用报错,需要补充xmlns:local="clr-namespace:İdaServis"(假设AboutPage、ItemsPage在项目根命名空间下)。

另外,TabBar里的LoginPage如果是应用启动页,建议通过路由导航跳转,避免启动时直接显示Flyout菜单。可以在AppShell的构造函数里添加启动导航逻辑:

public AppShell()
{
    InitializeComponent();
    // 启动时自动导航到LoginPage
    Shell.Current.GoToAsync("//LoginPage");
}

3. 替换原有的导航方式

把原来用PushModalAsync()的导航代码,替换为Shell的路由导航:

  • 原代码:await Navigation.PushModalAsync(new ProfilePage());
  • 替换为:await Shell.Current.GoToAsync("//ProfilePage");(注意Route要和ShellContent的Route属性完全一致)

4. 配置应用后台状态保留

应用切后台重启通常是Android启动模式问题,调整MainActivity.cs的[Activity]属性:

[Activity(Label = "İdaServis", 
          Icon = "@mipmap/icon", 
          Theme = "@style/MainTheme", 
          MainLauncher = true, 
          ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize,
          LaunchMode = LaunchMode.SingleTask)] // 添加该启动模式
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    // ... 原有代码
}

iOS默认支持后台状态保留,只要Info.plist里Application does not run in background设置为NO(默认值)即可。

三、验证测试

  1. 清理并重新生成项目,运行应用
  2. 导航到任意页面,切换到手机主屏幕后再返回,检查应用状态是否保留
  3. 测试所有页面的导航是否正常工作

内容的提问来源于stack exchange,提问作者Mert Altiparmak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:58:59