C# 在后面的代码中使用资源图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/774375/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:38:31  来源:igfitidea点击:

Using a resource image in code behind

c#wpfvisual-studioresources

提问by Dan Vogel

I need to dynamically change the background image applied to one of my buttons, but can't figure out how. The images are added to the project and have their Build Action set to Resource. I've tried the follow:

我需要动态更改应用于我的一个按钮的背景图像,但不知道如何更改。图像被添加到项目中,并将它们的构建操作设置为资源。我试过以下:

buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("/Images/InchDOWN.png",UriKind.Relative)));

This compiles successfully, but will crash with a DirectoryNotFoundException saying "Could not find a part of the path 'C:\Images\InchDOWN.png'."

这将成功编译,但会因 DirectoryNotFoundException 而崩溃,提示“找不到路径 'C:\Images\InchDOWN.png' 的一部分。”

I don't want the app to look for the image on disk. How can I use the image as an embedded resource? I would think it involves changing the Build Action to Embedded Resource, but how do I use this resource in the code behind?

我不希望应用程序在磁盘上查找图像。如何将图像用作嵌入资源?我认为这涉及将 Build Action 更改为 Embedded Resource,但是如何在后面的代码中使用此资源?

采纳答案by gcores

You have to build the image as a Resource NOTan embedded resource. Resource is there specifically to be used by WPF projects.

您必须将图像构建为资源而不是嵌入资源。资源是专门供 WPF 项目使用的。

To use it in procedural code:

在程序代码中使用它:

 buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Images/InchDOWN.png")));

This is a lot easier to do in XAML which I recommend.

这在我推荐的 XAML 中要容易得多。

Edit

编辑

I forgot a forward slash before Images, that could be the problem. Here is a MSDN article about pack Urisif you need more info.

我忘记了图像之前的正斜杠,这可能是问题所在。如果您需要更多信息,这里有一篇关于 pack UrisMSDN 文章

Maybe you should post a question stating what exactly you're trying to accomplish and hopefully discover different approaches to your multi-state button problem.

也许您应该发布一个问题,说明您究竟要完成什么,并希望发现解决多状态按钮问题的不同方法。