如何在 MouseLeftButtonDown 事件中两次更改按钮的背景图像?
How can I change the button's background image twice in MouseLeftButtonDown event?
我在 MainWindow.xaml.cs
中编写了以下事件处理程序。我想实现这样的效果,当业务逻辑为运行时,runbutton的背景图切换为powerOnOff1.png
,当业务逻辑结束时,背景图切换回powerOnOff0.png
。
private void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
BitmapImage ima0 = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
image.Source = ima0;
//business logic
......
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
BitmapImage ima1 = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
image.Source = ima1;
}
以上代码无效。它总是显示 powerOnOff0.png
背景图片。它需要多线程吗?
Does it require multithreading?
是的。您需要在后台线程上执行业务逻辑。最简单的方法是启动一个新任务并等待它:
private async void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
image.Source = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
await Task.Run(() =>
{
//business logic here
});
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
image.Source = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
}
我在 MainWindow.xaml.cs
中编写了以下事件处理程序。我想实现这样的效果,当业务逻辑为运行时,runbutton的背景图切换为powerOnOff1.png
,当业务逻辑结束时,背景图切换回powerOnOff0.png
。
private void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
BitmapImage ima0 = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
image.Source = ima0;
//business logic
......
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
BitmapImage ima1 = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
image.Source = ima1;
}
以上代码无效。它总是显示 powerOnOff0.png
背景图片。它需要多线程吗?
Does it require multithreading?
是的。您需要在后台线程上执行业务逻辑。最简单的方法是启动一个新任务并等待它:
private async void Run_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//set run button background image to powerOnOff1.png indicates business logic is going to run.
image.Source = new BitmapImage(new Uri("picture/powerOnOff1.png", UriKind.Relative));
await Task.Run(() =>
{
//business logic here
});
//restore Runbutton background image to powerOnOff0.png indicates business logic is finished.
image.Source = new BitmapImage(new Uri("picture/powerOnOff0.png", UriKind.Relative));
}