我想延迟我的循环,以便它显示我输入的背景颜色。现在,它太快了。
目标是让颜色闪烁以产生迪斯科效果。我使用了 Thread.Sleep
但这不起作用。
这是我目前的尝试:
private void Disco(object sender, RoutedEventArgs e)
{
for (int n =0; n<=10;n++)
{
Background = Brushes.Coral;
Background = Brushes.AliceBlue;
Background = Brushes.DarkRed;
Background = Brushes.Red;
Background = Brushes.Blue;
Background = Brushes.Aquamarine;
}
}
最佳答案
您可以使用 async
方法,@Jeroen van Langen 在评论中建议了这种方法。
在 Background
更改之间使用 await Task.Delay(time)
会将更改延迟给定的 time
。
private async void Disco(object sender, RoutedEventArgs e)
{
Background = Brushes.Coral;
await Task.Delay(500); // 500 is just an example. You can use any number in milliseconds.
Background = Brushes.AliceBlue;
await Task.Delay(500);
Background = Brushes.DarkRed;
await Task.Delay(500);
Background = Brushes.Red;
await Task.Delay(500);
Background = Brushes.Blue;
await Task.Delay(500);
Background = Brushes.Aquamarine;
await Task.Delay(500);
//Set the background back to its original color here.
}
如果您需要表单继续“跳迪斯科”,例如,再次按下按钮,您可以将它包装在一个 while
循环中,该循环将一直持续到 Button
被按下,或者 ToggleButton
被选中。
如果你走这条路,我建议你阅读 asynchronous programming documentation .这非常有帮助。
关于c# - 我怎样才能减慢我的 for 循环以便我可以看到颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58286069/