Using a resource image in code behind
Asked Answered
C

1

7

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'."

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?

Cacography answered 21/4, 2009 at 20:11 Comment(0)
S
10

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

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

Edit

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.

Slaton answered 21/4, 2009 at 22:14 Comment(1)
I've tried this and I get a NotSupportedException saying "The URI prefix is not recognized." I agree, setting the image would is easier in XAML, but my goal is a sort of multi-state button and don't know how to do that in XAML.Cacography

© 2022 - 2024 — McMap. All rights reserved.