Using a resource image in code

I need to dynamically change the background image applied to one of my buttons, but cannot figure out how to do this. Images are added to the project, and their assembly action is set to Resource. I tried the following:

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

It compiles successfully, but a DirectoryNotFoundException fails and causes the message "Could not find part of the path C: \ Images \ InchDOWN.png".

I do not want the application to look for an image on disk. How to use the image as an embedded resource? I would think that this is due to changing the Build action to Embedded Resource, but how can I use this resource in the code?

+6
c # visual-studio resources wpf
Apr 21 '09 at 20:11
source share
1 answer

You need to create an image as a resource of NOT an embedded resource. The resource is specifically designed for WPF projects.

To use it in procedural code:

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

This is much easier to do in XAML, which I recommend.

Edit

I forgot the scroll in front of the images, this could be a problem. Below is an article if you need more information.

Perhaps you should ask a question about what exactly you are trying to accomplish, and I hope you will find different approaches to the problem with several states.

+8
Apr 21 '09 at 22:14
source share



All Articles