In project practice, we may encounter the need to clear the content displayed on some controls only after a period of time.
Let's do this:
First of all, we need to pay attention to: if interface operation is involved in wpf, we must use the timer dispatcher time, which is specially designed for wpf. Otherwise, using other kinds of timers will prompt that interface resources are owned by other threads and cannot update the interface.
For the first time, we need to declare a dispatcher timer
private DispatcherTimer showTimer = new DispatcherTimer();
Then bind the timer to handle
showTimer.Tick += new EventHandler(SetNull);
private void SetNull(object sender,EventArgs e) { label1.Content = ""; }
After that, we will specify how long to trigger the timer binding method and turn on the timer
showTimer.Interval = new TimeSpan(0, 0, 0, 6); showTimer.Start();
All codes are as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; using System.Windows.Threading; namespace Make the content of the control disappear after a period of time { /// <summary> /// MainWindow.xaml Interaction logic of /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private DispatcherTimer showTimer = new DispatcherTimer(); private void Button_Click(object sender, RoutedEventArgs e) { SetLabel("jianjipan,Hello"); showTimer.Tick += new EventHandler(SetNull); showTimer.Interval = new TimeSpan(0, 0, 0, 6); showTimer.Start(); } private void SetLabel(string text) { label1.Content = text; } private void SetNull(object sender,EventArgs e) { label1.Content = ""; } } }
The effect is: after clicking the button button, the string "Jipan, hello" will appear on the label control. After 6s, the label control will not display any value
The source code is as follows: (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa