我想将文件嵌入到 .NET Standard 程序集中,并在 WPF 应用程序的 XAML 中使用它。
如果您将构建操作设置为Resource
在其他程序集中使用嵌入文件非常容易,但是您必须使用<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
and <UseWPF>true</UseWPF>
能够使用Resource
像这样构建动作:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Resource Include="Resources\Image.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="Resources\Image.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!