Xenofonos
Xenofonos

Reputation: 129

Change background image source on button click in wpf forms

My default background image is "lobby.jpg" and when I click the "Lights" button I want it to swap with "lobby1.jpg" and vice versa. These images are stored in "obj\Debug\Images\".

Also I'd like to implement relative(?) imagesource uris so that I can access the images on any machine (without using the whole uri, just the "obj\Debug\Images\").

Edit: So the main issue seems to be that I tried changing the window background without realising that it was getting "covered" by the grid background of the page. So what I did is I set the main window background to "lobby.jpg", I made the grid background invisible and used the code from the answer to swap between the 2 backgrounds.

Upvotes: 1

Views: 771

Answers (1)

user1576474
user1576474

Reputation: 674

You can use AppDomain basepath to exe (this is are simplest way)

var basePath= AppDomain.CurrentDomain.BaseDirectory;
var imageDirPath = $"{basePath}\\Images\\";

Example:

  bool clicked = false;
    private void button_Click(object sender, RoutedEventArgs e)
    {
        var basePath = AppDomain.CurrentDomain.BaseDirectory;
        var imageDirPath = $"{basePath}\\Images\\";
        if (clicked)
            image.Source = new BitmapImage(new Uri(imageDirPath+ "lobby.jpg"));
        else
            image.Source = new BitmapImage(new Uri(imageDirPath + "lobby1.jpg"));
        clicked = !clicked;
    }

Upvotes: 2

Related Questions