1

我在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背景图像。它需要多线程吗?

4

1 回答 1

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));
}
于 2019-01-07T12:36:29.283 回答