我想将文件嵌入.NET Standard程序集中,并在WPF应用程序中使用它。
[如果将构建动作设置为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!
如果引用复制到输出目录的内容文件,则可以使用路径而不是包URI。试试这个:
image.Source = new BitmapImage(new Uri($@"{System.AppContext.BaseDirectory}\Resources\Image.png",
UriKind.Absolute));