Change Background image in WPF using C#

5.1k Views Asked by At

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

There are 2 best solutions below

1
On BEST ANSWER

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" ... />
1
On

Try this:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/Yourapp;component/yourimage.png")));