.NET MAUI应用启动失败(仅需安卓/iOS支持)求解决方案
解决.NET MAUI仅适配安卓/iOS时的启动失败问题
错误回顾
当前遇到两类核心错误:
error NETSDK1136: The target platform must be set to Windows (usually by including '-windows' in the TargetFramework property) when using Windows Forms or WPF, or referencing projects or packages that do so.- XamlC类型解析错误:无法识别
Application、Shell、ResourceDictionary、ContentPage等MAUI核心类型
已尝试移除项目文件中Windows相关的TargetFrameworks和版本配置,但问题未解决。
针对性解决步骤
1. 彻底清理项目文件的多平台残留
确保项目文件(.csproj)仅保留安卓和iOS的目标框架,删除所有其他平台相关配置:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <!-- 仅保留安卓和iOS目标框架 --> <TargetFrameworks>net7.0-android;net7.0-ios</TargetFrameworks> <!-- 仅保留移动端的版本配置 --> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">33.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">16.1</SupportedOSPlatformVersion> <!-- 明确禁用WPF/WinForms --> <UseWPF>false</UseWPF> <UseWindowsForms>false</UseWindowsForms> </PropertyGroup> </Project>
2. 排查并移除依赖Windows的NuGet包
打开NuGet包管理器:
- 检查是否有标注支持Windows/WPF/WinForms的第三方包,这类包可能引入了Windows依赖
- 确认
Microsoft.Maui.Controls等官方MAUI包的版本与项目目标框架版本匹配 - 替换或移除不必要的Windows依赖包
3. 清理缓存并重建项目
- 手动删除项目根目录下的
bin和obj文件夹 - 在Visual Studio中依次执行:
清理解决方案→恢复NuGet包→重建解决方案 - 重启Visual Studio后尝试启动项目
4. 验证XAML文件的命名空间
检查所有XAML文件的根节点,确保使用MAUI官方命名空间,避免混入Xamarin或Windows的旧命名空间:
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourAppName.AppShell"> <!-- 页面内容 --> </Shell>
5. 删除Windows相关的目标导入语句
检查项目文件中是否存在类似以下的Windows目标导入,若有则删除:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v17.0\Microsoft.Windows.UI.Xaml.CSharp.targets" />
内容的提问来源于stack exchange,提问作者Duarte Somsen
相关产品推荐
相关产品推荐

