-1

I wanna call a method in a TextChanged event only if the event got not fired again within one second.

How can this be done in WPF (maybe using a DispatcherTimer)?

I currently use this code but it does not call MyAction() within Method:

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
}
  • It "never goes here" because `textchanged` is true, hence `!textchanged` is false. That said, you should not create a new DispatcherTimer in each call of `textBox1_TextChanged`. Instead, create the DispatcherTimer once, then only start it in TextChanged, and stop it in `Method`. – Clemens Dec 27 '15 at 22:03
  • @Clemens yes, I know that but how can I make a working version of my approach? – Moagggi Stoane Dec 27 '15 at 22:04

1 Answers1

0

Change your code to the following:

DispatcherTimer dispatcherTimer = new DispatcherTimer();

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    if (dispatcherTimer.IsEnabled)
    {
        dispatcherTimer.Stop();
    }
    dispatcherTimer.Start();
}

void Method()
{
    dispatcherTimer.Stop();
    MyAction();
}

And add this straight after your InitializeComponent(); line within your constructor:

dispatcherTimer.Tick += (o, s) => { Method(); };
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
cramopy
  • 3,459
  • 6
  • 28
  • 42