1

I'd like to change the background image of my WPF application by a button. I know how to do it using WindowsForms, but in WPF I failed. I found a solution already, but that solution would copy my background images to the output folder next to the Application.exe This is not really a solution that I desire. I would like to have the images stored inside my application.

Can somebody explain me detailed what I need to do [how to add the images to the program, especially the resource-properties, how to access them in C#....]. It seems like I am too stupid to set it up correctly :P

Thanks in advance

2 Answers2

2

Try this:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/Yourapp;component/yourimage.png")));
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

Firstly, add a Folder to your Solution (Right click -> Add -> Folder), name it something like "Resources" or something useful.

Then, simply add your desired image to the folder (Right click on folder -> Add -> Existing item).

Once it's been added, if you click on the image and open the Properties window (Alt+Enter), you'll see the Build Action is set to Resource and the Copy to Output Directory is set to Do not copy.

You can reference the image in C# using the following code:

this.Background = new BitmapImage(new Uri(@"pack://application:,,,/YourApp;component/YourFolder/YourImage.png"));

Or in XAML:

<Image Source="pack://application:,,,/YourApp;component/YourFolder/YourImage.png" ... />

Or:

<Image Source="/YourApp;component/YourFolder/YourImage.png" ... />
Mike Eason
  • 9,525
  • 2
  • 38
  • 63
  • Thanks alot, your solution worked perfectly. I only had to place the new BitmapImage inside a new ImageBrush –  Jun 15 '15 at 07:26