简体   繁体   English

一个接一个地改变标签的颜色

[英]Changing color of labels one after another

I have a window with some labels. 我有一个带有一些标签的窗口。 I want the BackColor of the labels to change depending of some tests I am running: 我希望标签的BackColor根据我正在运行的一些测试而改变:

private void btnStartTest_Click(object sender, EventArgs e)
    {
        if(Tests.FirstTest())
        {
            this.lblFirstTest.BackColor = Color.LawnGreen;
        }
        else
        {
            this.lblFirstTest.BackColor = Color.Red;
        }

        if(Tests.SecondTest())
        {
            this.lblSecondTest.BackColor = Color.LawnGreen;
        }
        else
        {
            this.lblSecondTest.BackColor = Color.Red;
        }

        //and so on...
    }

I want the labels to change color one after another to show progress. 我希望标签一个接一个地改变颜色以显示进度。 But right now the color change only takes effect at the end of the method. 但是现在颜色变化仅在方法结束时生效。 So all labels change color at the same time. 所以所有标签都会同时改变颜色。

Why is this? 为什么是这样? And what can I change to get the desired effect? 我可以改变什么才能获得理想的效果?

Perform a Refresh on the form after each colour change. 每次换色后在表单上执行Refresh That should force visual elements to be updated and redrawn, giving the desired effect. 这应该强制更新和重新绘制视觉元素,从而产生所需的效果。 This is the simplest way that does not involve threading. 这是不涉及线程的最简单方法。

就像BugFinder所说的那样......在不同的线程上运行该方法(Task.RunAsync(()=> {}))...但是在这种情况下你必须使用一个调度程序来为控件赋值(或者别的例外)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM