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

跨平台.NET7项目Windows下加载WPF组件PresentationFramework失败的解决方法

解决.NET 7跨平台项目中WPF组件加载失败问题

问题背景

跨平台.NET 7项目,Windows端采用WPF作为UI框架(以动态链接方式关联到主项目),Mac端使用Cocoa。Windows运行时出现以下错误:

System.IO.FileNotFoundException: 'Could not load file or assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.'

需在保持主项目跨平台特性(不改为.NET Framework)的前提下解决该问题。

解决方案

1. 条件性配置主项目的WPF依赖

修改主项目的.csproj文件,仅在Windows平台启用WPF SDK并引用相关依赖:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <!-- 仅Windows平台启用WPF支持 -->
    <UseWPF Condition="'$(OS)' == 'Windows_NT'">true</UseWPF>
  </PropertyGroup>

  <!-- 仅Windows平台引用WPF子项目 -->
  <ItemGroup Condition="'$(OS)' == 'Windows_NT'">
    <ProjectReference Include="..\YourWpfWindowProject\YourWpfWindowProject.csproj" />
  </ItemGroup>

  <!-- 条件性引入WPF框架依赖 -->
  <ItemGroup Condition="'$(OS)' == 'Windows_NT'">
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
  </ItemGroup>

</Project>

2. 配置WPF子项目为Windows专属

确保WPF子项目的.csproj指定Windows专属目标框架:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

</Project>

3. 代码中添加平台判断,延迟加载WPF逻辑

在主应用中通过运行时平台检测,仅在Windows环境下执行WPF相关代码,避免非Windows平台触发WPF程序集加载:

using System.Runtime.InteropServices;

// 主入口逻辑
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    OpenWpfWindow();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    OpenCocoaWindow();
}

// 封装WPF窗口逻辑,仅Windows下执行
private void OpenWpfWindow()
{
    // 此处编写WPF窗口打开代码,例如:
    // new YourWpfWindow().ShowDialog();
}

// Cocoa窗口逻辑
private void OpenCocoaWindow()
{
    // 此处编写Mac端Cocoa窗口打开代码
}

4. 验证输出目录

构建项目后,检查Windows平台的输出目录,确保WPF子项目的编译产物(.dll、.exe等)已被复制到主应用的输出路径中。若Visual Studio未自动处理,可在WPF子项目的.csproj中添加手动复制逻辑:

<ItemGroup Condition="'$(OS)' == 'Windows_NT'">
  <Content Include="$(OutputPath)\YourWpfWindowProject.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:16:14