在 WPF 应用程序中使用 .NET 标准程序集中的内容文件



我想在 .NET Standard 程序集中嵌入一个文件,并在 WPF 应用的 XAML 中使用它。

如果将生成操作设置为Resource则很容易在其他程序集中使用嵌入的文件,但必须使用<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"><UseWPF>true</UseWPF>才能使用Resource生成操作,如下所示:

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Resource Include="ResourcesImage.png" />
</ItemGroup>

然后,可以从另一个程序集使用此 Uri:

pack://application:,,,/ReferencedAssembly;component/Resources/Image.png

如图所示:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/pack-uris-in-wpf#resource-file-pack-uris

我的问题:

如果您只想<Project Sdk="Microsoft.NET.Sdk">而不需要<UseWPF>true</UseWPF>那么您必须使用Content生成操作,因为它不需要 WPF,如下所示:

https://learn.microsoft.com/en-us/visualstudio/ide/build-actions

并像这样使用它:

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Content Include="ResourcesImage.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

然后,您应该能够从另一个程序集使用此 Uri:

pack://application:,,,/Resources/Image.png

如图所示:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/pack-uris-in-wpf#content-file-pack-uris

但是我得到以下异常:

Exception thrown: 'System.Resources.MissingManifestResourceException' in System.Private.CoreLib.dll
Exception thrown: 'System.IO.IOException' in PresentationFramework.dll
Exception thrown: 'System.IO.IOException' in PresentationCore.dll
System.Windows.Data Error: 6 : 'TargetDefaultValueConverter' converter failed to convert value 'pack://application:,,,/Resources/Image.png' (type 'String'); fallback value will be used, if available. BindingExpression:Path=BackgroundImage; DataItem='NavigationNode' (HashCode=663215); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource') IOException:'System.IO.IOException: Cannot locate resource 'resources/image.png'.

我已经清理并重建了整个解决方案。

我做错了什么?

重要提示:我需要在 xaml 中使用包 URI - 太多了,无法将所有现有代码从 xaml 转换为 cs!

如果引用复制到输出目录的内容文件,则可以使用路径而不是包 URI。试试这个:

image.Source = new BitmapImage(new Uri($@"{System.AppContext.BaseDirectory}ResourcesImage.png",
UriKind.Absolute));

如果由于某种原因仍需要使用包 URI,请将路径中的pack://application:,,,替换为pack://siteoforigin:,,,,它应该可以工作。

相关内容

最新更新