简体   繁体   English

单击按钮后如何更改图像源?

[英]How to change an image source after clicking a button?

I'm using an Image as a button. 我正在使用Image作为按钮。 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 . 因此,默认情况下,我需要图像源为/image1.png ,当我单击图像时,它将创建一个if函数并将其图像源更改为/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". 图像以“ image1”开头。
  2. The constructor sets isPlaying to false 构造函数将isPlaying设置为false
  3. You click the button 您单击按钮
  4. The handler runs, since isPlaying is false , the image is set to "image1" (your first block) 该处理程序运行,因为isPlayingfalse ,所以图像设置为“ image1”(您的第一个块)
  5. isPlaying is set to true isPlaying设置为true
  6. You click the button again 您再次单击该按钮
  7. The handler runs again, since isPlaying is true the image is set to "image2". 该处理程序再次运行,因为isPlayingtrue所以图像设置为“ 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. 因此,当当前值为false时翻转设置的图像,或者将初始值设置为true即可获得您描述的行为。

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. Source属性应该绑定到您的View模型(通过转换器),并且按钮的Command更改该源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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