如果事件没有再次触发,如何调用方法
How to call a method if event got not fired again
我想在 TextChanged
事件中调用一个方法,前提是该事件在一秒内没有再次触发。
如何在 WPF
中完成(也许使用 DispatcherTimer
)?
我目前使用此代码,但它不会在 Method
:
内调用 MyAction()
bool textchanged = false;
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
textchanged = true;
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += (o, s) => { Method(); };
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Start();
}
void Method()
{
if (!textchanged) //here always false
{
//never goes here
MyAction();
}
//always goes here
}
将您的代码更改为以下内容:
DispatcherTimer dispatcherTimer = new DispatcherTimer();
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (dispatcherTimer.IsEnabled)
{
dispatcherTimer.Stop();
}
dispatcherTimer.Start();
}
void Method()
{
dispatcherTimer.Stop();
MyAction();
}
并在构造函数中的 InitializeComponent();
行之后直接添加:
dispatcherTimer.Tick += (o, s) => { Method(); };
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
我想在 TextChanged
事件中调用一个方法,前提是该事件在一秒内没有再次触发。
如何在 WPF
中完成(也许使用 DispatcherTimer
)?
我目前使用此代码,但它不会在 Method
:
MyAction()
bool textchanged = false;
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
textchanged = true;
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += (o, s) => { Method(); };
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Start();
}
void Method()
{
if (!textchanged) //here always false
{
//never goes here
MyAction();
}
//always goes here
}
将您的代码更改为以下内容:
DispatcherTimer dispatcherTimer = new DispatcherTimer();
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (dispatcherTimer.IsEnabled)
{
dispatcherTimer.Stop();
}
dispatcherTimer.Start();
}
void Method()
{
dispatcherTimer.Stop();
MyAction();
}
并在构造函数中的 InitializeComponent();
行之后直接添加:
dispatcherTimer.Tick += (o, s) => { Method(); };
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);