如何在MouseLeftButtonDown事件中两次更改按钮的背景图像?

时间:2019-01-07 12:34:18

标签: wpf button background-image mouseleftbuttondown

我在MainWindow.xaml.cs中编写以下事件处理程序。我想实现这种效果,当业务逻辑运行时,运行按钮的背景图像切换到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背景图片。是否需要多线程?

1 个答案:

答案 0 :(得分:0)

  

是否需要多线程?

是的。您需要在后台线程上执行业务逻辑。最简单的方法是开始一个新任务并等待它:

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