从上次单击 c# WPF 开始在短时间内更改按钮颜色



>我使用此链接来解决我的问题,但取得了部分成功
短时间更改按钮颜色

我需要显示一个红色按钮。
每当单击按钮时,它都会将其颜色更改为绿色 5 秒,应支持连续点击,但不应累积,即按钮颜色应在最后一次点击后 5 秒变回红色。

我的代码:

private void myButton_Click(object sender, RoutedEventArgs e)
{
    Timer timer = new Timer { Interval = 5000 };
    timer.Elapsed += HandleTimerTick;
    myButton.Background = new SolidColorBrush(Colors.LightGreen);
    timer.Start();
}
private void HandleTimerTick(object sender, EventArgs e)
{
    Timer timer = (Timer)sender;
    timer.Stop();
    myButton.Dispatcher.BeginInvoke((Action)delegate()
    {
        myButton.Background = new SolidColorBrush(Colors.Red);
    });          
}

它可以工作,但距离我第一次单击只有 5 秒,并且每次单击按钮时计时器都不会重置。
感谢您的帮助。

您必须将计时器移出事件,并在用户每次单击时重新启动它。大致如下:

 public partial class MainWindow : Window
    {
        private Timer timer;
        public MainWindow()
        {
            InitializeComponent();
            timer = new Timer{Interval = 5000};
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {               
            timer.Elapsed += HandleTimerTick;
            myButton.Background = new SolidColorBrush(Colors.LightGreen);
            timer.Stop();
            timer.Start();
        }
        private void HandleTimerTick(object sender, EventArgs e)
        {
            Timer timer = (Timer)sender;
            timer.Stop();
            myButton.Dispatcher.BeginInvoke((Action)delegate()
            {
                myButton.Background = new SolidColorBrush(Colors.Red);
            });
        }
    }

最新更新