gpt4 book ai didi

c# - 在 WPF 应用程序中使用来自 .NET Standard 程序集的内容文件

转载 作者:行者123 更新时间:2023-12-04 09:57:48 40 4
gpt4 key购买 nike

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

如果将构建操作设置为 Resource在其他程序集中使用嵌入文件非常容易,但你必须使用 <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"><UseWPF>true</UseWPF>能够使用 Resource像这样构建 Action :

  <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 中使用 pack URI - 太多了,无法将所有现有代码从 xaml 转换为 cs!

最佳答案

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

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

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

关于c# - 在 WPF 应用程序中使用来自 .NET Standard 程序集的内容文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61886599/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com