[英]How can I in c# switch input field background color (white/red) on wait?
如何在C#中等待时切换输入字段的背景色(白色/红色)?
我是C#的初学者,问题很可能很简单...欢迎任何建议。 谢谢!
我不明白你到底想要什么。 你可以做这样的事情
您可以使用Task.Delay()
等待
switch (id)
{
case 1:
await Task.Delay(2000);
this.BackColor = System.Drawing.Color.Red;
break;
case 2:
await Task.Delay(2000);
this.BackColor = System.Drawing.Color.White;
break;
}
对于“窗口窗体” ,如果要每两秒钟更改一次颜色,则可以使用计时器控件。 将此代码放在您的等待代码中
var timer = new Timer() { Interval = 2000, Enabled = true, };
timer.Tick += (s, e) =>
this.BackColor =
this.BackColor == Color.Red ? Color.White: Color.Red;
在WPF(无MVVM)中,使用TextBox作为输入字段。 在您的.xaml文件中创建它。
<Window x:Class="TestWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="MyTextBox" Background="Red" Margin="188,134,200.4,161.4"/>
</Grid>
</Window>
在您的后台代码中,也要编写此代码。
using System.Threading;
using System.Windows;
using System.Windows.Media;
namespace TestWPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
int duration = 10; //Change this number to change the total flash duration
double interval = 0.5; //Change this number to increase/decrease the interval between color changes.
Thread t = new Thread(() => FlashColor(duration, interval));
t.Start();
}
private void FlashColor(int duration, double interval)
{
for (int counter = 0; counter < (int) (duration/interval); counter++)
{
Dispatcher.Invoke(() => ChangeColor(Brushes.White));
Thread.Sleep((int) (interval*1000));
Dispatcher.Invoke(() => ChangeColor(Brushes.Red));
Thread.Sleep((int) (interval*1000));
}
}
public void ChangeColor(SolidColorBrush color)
{
MyTextBox.Background = color;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.