Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果事件未再次触发,如何调用方法_C#_Wpf_Dispatchertimer - Fatal编程技术网

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是的,我知道这一点,但我如何才能为我的方法创建一个工作版本?