在 WPF 中,如何使用 XAML 指定嵌套在目录中的文件的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/278943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In WPF how do I specify the path to a file nested in a Directory using XAML?
提问by Doug
I am trying to do this...
我正在努力做到这一点......
<Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" />
But I get this error...
但我收到这个错误...
Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'. Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.
无法将属性“Source”中的字符串“Images\unlock.png”转换为“System.Windows.Media.ImageSource”类型的对象。无法找到资源“forms/images/unlock.png”。标记文件“Fuse;component/forms/mainwindow.xaml”第 273 行第 51 行中的对象“System.Windows.HierarchicalDataTemplate”出错。
As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?
如您所见,包含此 XAML 的表单位于名为 Forms 的文件夹中。我的图像位于名为图像的文件夹中。如何从表单映射到图像?
I tried Source="..Images\unlock.png"
which does not work in WPF.
我试过Source="..Images\unlock.png"
哪个在 WPF 中不起作用。
Any help?
有什么帮助吗?
回答by Matt Hamilton
回答by Jamal
- Add your image to the Project in VS
- Right click on that image unlock.png
- Go to Context menu /Properties
- Change Build Action to Resource
- 将您的图像添加到 VS 中的项目
- 右键单击该图像unlock.png
- 转到上下文菜单/属性
- 将构建操作更改为资源
Thats it :-)
就是这样 :-)
回答by Hekkaryk
In order to use resource located in folder different that the one where your XAML is, do this:
为了使用位于与 XAML 所在文件夹不同的文件夹中的资源,请执行以下操作:
<Image Source="pack://application:,,,/Resources/image.png"/>
Where Resourcesis name of directory which you want to use resources from and image.png isname of image to display. Answer found thanks to @matt-hamilton and @brian-hinchey and their mention of Pack URI.
Works perfectly with your own Converters. You just have to return string matching schema above.
其中Resources是您要使用资源的目录名称,而image.png 是要显示的图像名称。感谢@matt-hamilton 和@brian-hinchey 以及他们对 Pack URI 的提及找到了答案。
与您自己的转换器完美配合。您只需要返回上面的字符串匹配模式。
回答by Hekkaryk
Have you tried setting the source to a BitmapImage?
您是否尝试将源设置为BitmapImage?
<Image x:Name="imgGroupImage" Margin="0,0,5,0" >
<Image.Source>
<BitmapImage UriSource="Images/unlock.png" />
</Image.Source>
</Image>
I believe the default type of Uri
for UriSource
is a relative Uri
, which works off the application's base class. You might find you can configure the BitmapSource
a bit easier than trying to find the exact way you have to enter the file path in the Source
attribute.
我相信Uri
for的默认类型UriSource
是 relative Uri
,它适用于应用程序的基类。您可能会发现,BitmapSource
与尝试找到在Source
属性中输入文件路径的确切方式相比,您可以更轻松地配置它。