在运行时设置 WPF 图像控件的源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22105388/
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
Setting the Source of a WPF Image Control at runtime
提问by hendersondayton
I have an Image control in a WPF Window named "Image1". I am trying to set the picture that is displayed with a png file that I added as a resource.
我在名为“Image1”的 WPF 窗口中有一个 Image 控件。我正在尝试设置与我作为资源添加的 png 文件一起显示的图片。
I am really struggling to figure out how to do it.
我真的很难弄清楚如何去做。
I am using VB.Net and I am new to it.
我正在使用 VB.Net,我是新手。
EDIT: I found this while waiting for help:
编辑:我在等待帮助时发现了这个:
Image1.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/images/imagenamehere", UriKind.Relative))
回答by Sheridan
If you have added your images to a folder named imagesin the root of your project using the Add Existing Itemcommand in Visual Studio, then you can reference your images in a simpler way than you have displayed in your edit. There is no need to use a BitMapImageeither. You can set the Image.Sourceproperty, either at design time, or at runtime like this:
如果已images使用Visual Studio 中的“添加现有项”命令将图像添加到项目根目录中命名的文件夹中,则可以以比在编辑中显示的方式更简单的方式引用图像。也不需要使用 a BitMapImage。您可以Image.Source在设计时或运行时设置属性,如下所示:
Image.Source = "/ApplicationName;component/images/ImageName.png";
Although, I'd like to add that in WPF, the best way to set an Image.Sourceat runtime is with a Binding. In this respect, you'd change the stringproperty that was data bound to the Image.Sourceproperty to the above stringto change the image.
虽然,我想在 WPF 中添加它,但Image.Source在运行时设置 的最佳方法是使用Binding. 在这方面,您将string数据绑定到Image.Source属性的属性更改为上述属性string以更改图像。
回答by Crow1973
I tried to set the icon property of a window like mentioned above but it returned an error. I search and found a solution. I don't know if it is the best solution but maybe someone has got the same problem.
我试图像上面提到的那样设置窗口的图标属性,但它返回了一个错误。我搜索并找到了解决方案。我不知道这是否是最好的解决方案,但也许有人遇到了同样的问题。
Solution:
解决方案:
windowX.Icon = BitmapFrame.Create(Application.GetResourceStream(New Uri("Resources\addX.png", UriKind.RelativeOrAbsolute)).Stream)

