简体   繁体   中英

How to change an image source after clicking a button?

I'm using an Image as a button. So I need the image source to be /image1.png by default, and when I click the Image, it will make an if function and change its image source to /image2.png . I changes the image correctly, the problem is that I have to click two times the image to change when it is first clicked.

This is what I'm using:

public MainWindow()
    {
        InitializeComponent();
        IsPlaying = false;
        //PlayBtn.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\Users\myusername\Documents\Visual Studio 2013\Projects\Project1\Project1WPF\image1.png");
    }

private void PlayBtn_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(IsPlaying == false)
        {

            PlayBtn.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\Users\myusername\Documents\Visual Studio 2013\Projects\Project1\Project1WPF\image1.png");
            IsPlaying = true;
        }else if(IsPlaying == true)
        {

            PlayBtn.Source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\Users\myusername\Documents\Visual Studio 2013\Projects\Project1\Project1WPF\image2.png");
            IsPlaying = false;
        }       

To fix your problem, simply set the initial state correctly. As it stands, you have this:

  1. The image starts with "image1".
  2. The constructor sets isPlaying to false
  3. You click the button
  4. The handler runs, since isPlaying is false , the image is set to "image1" (your first block)
  5. isPlaying is set to true
  6. You click the button again
  7. The handler runs again, since isPlaying is true the image is set to "image2".

So either flip which image is set when the current value is false , or set the initial value to true to get the behavior you describe.

As an aside, you probably shouldn't be doing this in the code-behind at all. The Source property should be bound to your View Model (through a converter) and the button's Command changes that source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM