在后面的代码中使用资源映像 [英] Using a resource image in code behind

查看:95
本文介绍了在后面的代码中使用资源映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态更改应用于我的一个按钮的背景图像,但不知道如何操作.这些图像已添加到项目中,并且其构建操作"设置为资源".我尝试了以下方法:

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)));

这将成功编译,但是将失败并显示DirectoryNotFoundException,提示找不到路径'C:\ Images \ InchDOWN.png'的一部分".

This compiles successfully, but will crash with a DirectoryNotFoundException saying "Could not find a part of the path '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?

推荐答案

您必须将图像构建为资源 NOT (嵌入式资源).资源专门供WPF项目使用.

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

要在程序代码中使用它:

To use it in procedural code:

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

在我建议的XAML中,这要容易得多.

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

修改

我在Images之前忘记了正斜杠,这可能是问题所在.如果您需要更多信息,请参见有关Uris包的MSDN文章.

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

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

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.

这篇关于在后面的代码中使用资源映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆