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

WinUI3发布生成的EXE启动时抛出XamlParseException问题求助

问题

程序在Visual Studio中直接启动或从Debug目录运行时完全正常,但通过Visual Studio发布命令或dotnet publish命令发布后,启动会抛出XAML解析异常,具体报错信息如下:

Microsoft.UI.Xaml.Markup.XamlParseException: XAML parsing failed.
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|20_0(Int32 hr)
   at ABI.Microsoft.UI.Xaml.IApplicationStaticsMethods.LoadComponent(IObjectReference _obj, Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)

已尝试以下所有发布配置组合,均出现相同异常:

  • Debug/Release模式切换
  • Self-contained部署
  • 单文件(Single file)发布
  • ReadyToRun编译优化

当前项目配置如下:

<TargetFramework>net7.0-windows10.0.22000.0</TargetFramework>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.4.230822000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.756" />
解决方案

1. 检查XAML资源引用路径

发布后XAML解析失败最常见的原因是资源(图片、样式、字典等)的引用路径在发布环境下无法正确寻址。确保所有XAML中的资源使用项目相对路径,避免硬编码Debug目录或绝对路径。

错误示例:

<Image Source="C:\MyProject\Debug\Assets\icon.png" />

正确示例:

<Image Source="Assets/icon.png" />

2. 确认资源文件发布时被正确复制

检查项目文件中资源的CopyToOutputDirectory设置,确保需要的资源会被复制到发布目录:

<ItemGroup>
  <!-- 匹配所有Assets目录下的文件 -->
  <Content Include="Assets\**" CopyToOutputDirectory="PreserveNewest" />
  <!-- 匹配所有样式文件 -->
  <Content Include="Styles\**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

3. 修复Windows App SDK发布依赖问题

针对Windows App SDK项目,发布时可能存在SDK依赖未正确打包的情况,可尝试:

  • 将Windows App SDK升级到最新稳定版本(1.4版本后续有补丁更新,兼容性更好)
  • 在项目文件中明确打包类型配置:
<!-- 若不需要打包为MSIX,设置为None;需要MSIX则设为MSIX -->
<WindowsPackageType>None</WindowsPackageType>

4. 单文件发布的特殊配置(若使用单文件)

单文件发布时,XAML相关的原生资源可能无法被正确嵌入,需在项目文件中添加以下配置:

<PropertyGroup>
  <PublishSingleFile>true</PublishSingleFile>
  <SelfContained>true</SelfContained>
  <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
</PropertyGroup>

5. 捕获详细异常信息

在App.xaml.cs的OnLaunched方法中添加异常捕获,输出更详细的错误日志,定位具体哪个XAML文件或资源解析失败:

protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
    try
    {
        MainWindow window = new MainWindow();
        window.Activate();
    }
    catch (Exception ex)
    {
        // 将详细错误写入日志文件
        File.WriteAllText("launch_error.log", $"{ex.Message}\r\n{ex.StackTrace}\r\n{ex.InnerException?.Message}");
        throw;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:05:07