【发布时间】:2020-09-05 06:07:43
【问题描述】:
我想在 .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="Resources\Image.png" />
</ItemGroup>
然后你可以从另一个程序集中使用这个 Uri:
pack://application:,,,/ReferencedAssembly;component/Resources/Image.png
如下所示:
我的问题:
如果您只需要<Project Sdk="Microsoft.NET.Sdk"> 而不需要<UseWPF>true</UseWPF>,那么您必须使用Content 构建操作,因为它不需要WPF,如下所示:
https://docs.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
如下所示:
但我得到以下异常:
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!
【问题讨论】:
标签: c# wpf .net-core msbuild .net-standard