Question

I need to change the background image at runtime, based on which RadioButton the user clicks. I'm doing this in a WPF project in Visual Studio, and I need to put the code in the Checked event in the xaml.cs file

I have an Image control called imgBackground, with 6 images in its Source collection, which are listed in an Images folder in the Solution Explorer.

I've tried:

this.imgBackground.Source = "filename.jpg";

both with and without the quotes, and with various paths (I've tried too many different variations to list them all here) and nothing works - everything I've tried just gives an error in the editor, before I even try to build and run anything (the error given varies depending on what I'm trying at the time).

Was it helpful?

Solution

If you are using relative paths as filenames like

this.imgBackground.Source = "filename.jpg";

then these files must be in the same directory as the .exe of your program is. One workaround would be to use absolute paths like

this.imgBackground.Source = @"C:\MyFolder\MyProject\filename.jpg";

Or, even further use the packaging mechanism of WPF or pack your images as resources into your assembly. Look at this thread.

EDIT:

For your clarification:

The Source-property demands an System.Windows.Media.ImageSource-object, which you must provide. Do it like this:

BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri("filename.jpg", UriKind.Relative);
bi3.EndInit();
this.imgBackground.Source = bi3;

Please refer to this documentation here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top