c# - 我怎样才能减慢我的 for 循环以便我可以看到颜色?

标签 c# xaml

我想延迟我的循环,以便它显示我输入的背景颜色。现在,它太快了。

目标是让颜色闪烁以产生迪斯科效果。我使用了 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/

相关文章:

xaml - 为什么从计时器引发 PropertyChanged 事件会导致 COMException?

c# - 在 Outlook 中检索当前电子邮件正文

c# - 将 FlipView 与 ObservableCollection<writeablebitmap> 绑定(bind)

c# - 如何从命令行调用多个文件到您的应用程序中?

c# - 使用 Roslyn 将类(class)成员添加到特定位置?

c# - 当 ObservableCollection 从 View 模型公开时,如何对从 ObservableCollection 公开的属性进行数据绑定(bind)?

c# - 绑定(bind)到 WPF 中的设计数据

c# - Xamarin Forms 找不到如何将对象与详细信息 View 绑定(bind)

c# - 在 System.Windows.Form 派生类中的何处配置资源?

c# - 使 FlowDocument 光标在 RichTextBox 中垂直居中