C# 来自项目资源的 WPF 绑定图像源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18041766/
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
WPF Binding image source from Project Resources
提问by oimitro
Ok i have in my project Resources about 5 Images
. What i want to do is to Bind an Image.Source
from my Project Resources. Im C# code its pretty easy, i just do :
好的,我在我的项目资源中有大约 5 Images
。我想要做的是Image.Source
从我的项目资源中绑定一个。我的 C# 代码很简单,我只是这样做:
ImageHolder.Source = Propetries.Resources.Image1.png
.
ImageHolder.Source = Propetries.Resources.Image1.png
.
How can this be done in XAML? Something like this :
这如何在 XAML 中完成?像这样的事情:
<Image Source={??????}/>
Thanks in advance.
提前致谢。
回答by Rohit Vats
Make sure your Build Action
for image
is marked as Resource
and then you can simply do this in your XAML -
确保您的Build Action
forimage
被标记为Resource
,然后您可以在 XAML 中简单地执行此操作 -
<Image Source="Properties/Resources/a.png"/>
Assuming Propetries/Resources
is folder structure in your project where your image is present.
假设Propetries/Resources
您的项目中存在您的图像的文件夹结构。
回答by knov
Visual studio will create Resources folder and put your image file into it when you add image to the resx file.
当您将图像添加到 resx 文件时,Visual Studio 将创建 Resources 文件夹并将您的图像文件放入其中。
In order to use this image in binding you will need to change build action from None to Resource. After that you can bind as follows:
为了在绑定中使用此图像,您需要将构建操作从无更改为资源。之后,您可以按如下方式绑定:
<Image Source="Resources/your_image_name.png"/>
You can not bind directly to Propetries.Resources.your_image_name because of you will need to convert System.Drawing.Bitmap to WPF BitmapSource. But you can bind to strings in the Resource.resx:
您不能直接绑定到 Propetries.Resources.your_image_name,因为您需要将 System.Drawing.Bitmap 转换为 WPF BitmapSource。但是您可以绑定到 Resource.resx 中的字符串:
<TextBlock Text="{x:Static properties:Resources.YourStringResource}"></TextBlock>
Read here how to convert System.Darwing.Bitmap to the WPF bitmap: Load a WPF BitmapImage from a System.Drawing.Bitmap
在此处阅读如何将 System.Darwing.Bitmap 转换为 WPF 位图:从 System.Drawing.Bitmap 加载 WPF BitmapImage
And here about binding to the values in the resx file: Get values from *.resx files in XAML
这里是关于绑定到 resx 文件中的值: Get values from *.resx files in XAML