以下解决方案适用于 wpf 应用程序。当您启动计时器时,将启动一个单独的线程。要从该线程更新 UI,您必须使用 dispatch 方法。请阅读代码中的注释并相应地使用代码。必需的标头
使用 System.Timers;
private void DisplayWarning(String message, int Interval = 3000)
{
Timer timer = new Timer();
timer.Interval = Interval;
lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Content = message));
lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Visibility = Visibility.Visible));
// above two line sets the visibility and shows the message and interval elapses hide the visibility of the label. Elapsed will we called after Start() method.
timer.Elapsed += (s, en) => {
lblWarning.Dispatcher.Invoke(new Action(() => lblWarning.Visibility = Visibility.Hidden));
timer.Stop(); // Stop the timer(otherwise keeps on calling)
};
timer.Start(); // Starts the timer.
}
用法 :
DisplayWarning("Warning message"); // from your code