C# 单击按钮后如何更改图像源?
我正在使用C# 单击按钮后如何更改图像源?,c#,wpf,image,C#,Wpf,Image,我正在使用图像作为按钮。因此,默认情况下,我需要图像源为/image1.png,当我单击图像时,它将生成if函数,并将其图像源更改为/image2.png。我正确地更改了图像,问题是当第一次单击图像时,我必须单击两次图像才能进行更改 这就是我正在使用的: public MainWindow() { InitializeComponent(); IsPlaying = false; //PlayBtn.Source = (ImageSourc
图像
作为按钮。因此,默认情况下,我需要图像源为/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;
}
要解决问题,只需正确设置初始状态。就目前情况而言,您有:
isplay
设置为false
isplay
是false
,所以图像被设置为“image1”(您的第一个块)isplay
设置为true
isplay
为true
图像设置为“image2”false
时设置的图像,要么将初始值设置为true
,以获得您描述的行为
顺便说一句,您可能根本不应该在代码背后这样做。
Source
属性应该绑定到视图模型(通过转换器),按钮的命令将更改该源。Ok,那么我应该将初始值更改为true?对吗?@ChrisCreateBoss可能,只要这在程序的其余部分有意义。