如何将 WPF BitmapImage UriSource 属性设置为相对路径? [英] How can I set the WPF BitmapImage UriSource property to a relative path?
问题描述
我正在使用 BitmapImage 类在 WPF 中加载图像.当我为 UriSource 提供绝对路径时,我的代码可以完美运行,但当我尝试使用相对路径时却不能.
I'm loading an image in WPF by using the BitmapImage class. My code works perfectly when I give an absolute path for the UriSource but not when I try and use a relative path.
我的 XAML 是:
<Image Width="50" Name="MemberImage" HorizontalAlignment="Left">
<Image.Source>
<BitmapImage DecodePixelWidth="50" UriSource="questionmark.jpg" />
</Image.Source>
</Image>
将 questionmark.jpg 添加到项目中,并将资源和复制到输出目录的构建操作设置为始终复制.我得到的错误是文件 [文件名] 不是项目的一部分或其‘构建操作’属性未设置为‘资源’".这在我使用 UriSource 的绝对路径时有效,但显然不行.
The questionmark.jpg is added to the project with a Build Action of Resource and Copy to Output Directory set to Copy always. The error I get is "The file [file name] is not part of the project or its 'Build Action' property is not set to 'Resource'". This works when I use an absolute path for the UriSource but that obviously won't do.
我应该如何在 XAML 中定义我的 UriSource?
How should I be defining my UriSource in the XAML?
推荐答案
我认为一旦图像位于资源中,您就不需要将其复制到输出目录.
I don't think you need to copy the image to output directory once it's in resource.
正确的指定方式是
<BitmapImage
x:Key = "Logo"
UriSource = "pack://application:,,,/ApplicationNamespace;component/Images/App/image.png"
/>
直接替换
ApplicationNamespace
与您的应用程序命名空间
ApplicationNamespace
with your application namespace
和
Images/App/image.png
带有你在项目中的图片路径
Images/App/image.png
with your image path in the project
这篇关于如何将 WPF BitmapImage UriSource 属性设置为相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!