单击按钮后如何更改图像源?
How to change an image source after clicking a button?
我正在使用 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;
}
要解决您的问题,只需正确设置初始状态即可。就目前而言,你有这个:
- 图像以 "image1" 开头。
- 构造函数将
isPlaying
设置为false
- 你点击按钮
- 处理程序运行,因为
isPlaying
是 false
,图像设置为 "image1"(您的第一个块)
isPlaying
设置为 true
- 您再次点击按钮
- 处理程序再次运行,因为
isPlaying
是 true
图像设置为 "image2"。
因此,要么翻转当前值为 false
时设置的图像,要么将初始值设置为 true
以获得您描述的行为。
顺便说一句,您可能根本不应该在代码隐藏中这样做。 Source
属性 应该绑定到您的视图模型(通过转换器)并且按钮的 Command
会更改该源。
我正在使用 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;
}
要解决您的问题,只需正确设置初始状态即可。就目前而言,你有这个:
- 图像以 "image1" 开头。
- 构造函数将
isPlaying
设置为false
- 你点击按钮
- 处理程序运行,因为
isPlaying
是false
,图像设置为 "image1"(您的第一个块) isPlaying
设置为true
- 您再次点击按钮
- 处理程序再次运行,因为
isPlaying
是true
图像设置为 "image2"。
因此,要么翻转当前值为 false
时设置的图像,要么将初始值设置为 true
以获得您描述的行为。
顺便说一句,您可能根本不应该在代码隐藏中这样做。 Source
属性 应该绑定到您的视图模型(通过转换器)并且按钮的 Command
会更改该源。