简体   繁体   English

更改按钮的颜色和文本一段时间

[英]Change color and text of button for a certain period of time

I have to change the text and color of a button while the Click Event has occured, but just for a few seconds, then the old values for text and color should appear. 单击事件发生时,我必须更改按钮的文本和颜色,但是只需几秒钟,然后应该显示文本和颜色的旧值。

How could this work? 这怎么工作? Maybe with a async task, which reset the values after the time is elapsed? 也许使用异步任务,该任务在经过时间后会重置值?

The problem is I recognized that the color and the text will be updated only after the click event method has finished. 问题是我认识到只有在click事件方法完成后才会更新颜色和文本。

I am currently doing lot of research on async and await and currently somewhat addicted to it. 我目前在异步和等待方面进行了大量研究,目前对它有些上瘾。 So I could not stop myself from answering this one. 因此我无法阻止自己回答这一问题。

Check out a small sample, below : 查看以下小样本:

XAML Code: XAML代码:

<Grid >
    <Button x:Name="Button1" Content="Click Me" Width="88" Height="44" Click="Button1_Click"/>
</Grid>

Code Behind : 背后的代码:

private async void Button1_Click(object sender, RoutedEventArgs e)
{
    Button1.Background = Brushes.Red;
    Button1.Content = "Clicked State";
    await Task.Delay(8000);
    Button1.Background = Brushes.Transparent;
    Button1.Content = "Click Me";
}

Now let me explain what's happening here : 现在让我解释一下这里发生了什么:

  1. When the button is clicked, it will enter the async button clicked event handler Button1_Click. 当单击按钮时,它将进入异步按钮单击事件处理程序Button1_Click。

  2. The button color is changed to red and content changed to "Clicked State". 按钮颜色更改为红色,内容更改为“单击状态”。

  3. Now we can call await Task.Delay(8000), ie the execution of the function is now waiting for the task to complete, which is delayed by 8 seconds. 现在我们可以调用await Task.Delay(8000),即函数的执行现在正在等待任务完成,这延迟了8秒。 The execution returns to the main UI thread and your UI is still responsive. 执行返回到主UI线程,您的UI仍然响应。

  4. After 8 seconds is complete, a free thread from the thread pool will again start executing the rest of the method, after await. 8秒后,线程池中的空闲线程将在等待后再次开始执行该方法的其余部分。

  5. The button is changed to default background color and content is changed to "Click Me" which was the default content. 该按钮更改为默认背景色,并且内容更改为默认内容“ Click Me”。

Hope this helps. 希望这可以帮助。

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

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