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

时间:2015-01-23 21:43:04

标签: c# wpf image

我正在使用Image作为按钮。因此,默认情况下我需要将图片源设为/image1.png,当我点击图片时,它会生成if函数并将其图片源更改为/image2.png。我正确地更改了图像,问题是我必须单击两次图像才能在第一次单击时进行更改。

这就是我正在使用的:

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;
        }       

1 个答案:

答案 0 :(得分:0)

要解决您的问题,只需正确设置初始状态即可。就目前而言,你有这个:

  1. 图像以" image1"。
  2. 开头
  3. 构造函数将isPlaying设置为false
  4. 您点击按钮
  5. 处理程序运行,因为isPlayingfalse,图像设置为" image1" (你的第一个街区)
  6. isPlaying设置为true
  7. 您再次点击该按钮
  8. 处理程序再次运行,因为isPlayingtrue,图像设置为" image2"。
  9. 因此,当当前值为false时,要么翻转哪个图像,要么将初始值设置为true以获得您描述的行为。

    顺便说一句,你可能根本不应该在代码隐藏中这样做。 Source属性应绑定到您的视图模型(通过转换器),并且按钮的Command更改该源。