C# 如果事件未再次触发,如何调用方法
我只想在C# 如果事件未再次触发,如何调用方法,c#,wpf,dispatchertimer,C#,Wpf,Dispatchertimer,我只想在TextChanged事件中调用一个方法,前提是该事件在一秒钟内没有再次触发 如何在WPF(可能使用调度程序)中执行此操作 我当前使用此代码,但它没有在方法中调用MyAction(): bool textchanged = false; private void textBox1_TextChanged(object sender, TextChangedEventArgs e) { textchanged = true; DispatcherTimer dispatc
TextChanged
事件中调用一个方法,前提是该事件在一秒钟内没有再次触发
如何在WPF
(可能使用调度程序
)中执行此操作
我当前使用此代码,但它没有在方法中调用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
是真的,因此!textchanged
为false。也就是说,您不应该在textBox1\u TextChanged
的每次调用中创建新的Dispatchermer。相反,创建一次Dispatcher,然后只在TextChanged中启动它,然后在方法中停止它
@Clemens是的,我知道这一点,但我如何才能为我的方法创建一个工作版本?