MarkKGreenway
MarkKGreenway

Reputation: 8754

Silverlight Timer-Like Functionality

So what I have is a textbox that submits data back to the server.

I want to have it submit once the person has stopped typing.

My thought process was to have a timer and have the textbox change set the timer to start (if stopped) and reset the countdown time to lets say 3 seconds if its already running and have the timer.Tick event submit the changes...

Is there a better method for doing that?

Is there one that works?

Upvotes: 2

Views: 682

Answers (3)

PL.
PL.

Reputation: 2195

A better way would be to use RX framework that comes either as a separate download or with Silverlight Toolkit:

Observable
    .FromEvent<KeyEventArgs>(MyTextBox, "KeyUp")
    .Select(_ => MyTextBox.Text)
    .Throttle(TimeSpan.FromSeconds(3))
    .Subscribe(SubmitWord);

Upvotes: 2

Michael S. Scherotter
Michael S. Scherotter

Reputation: 10785

Use the DispatcherTimer class.

Upvotes: 1

Bryant
Bryant

Reputation: 8670

You can use a DispatcherTimer to do this. Just start the timer when the textbox gets focus and whenever the keydown event happens mark a variable that notes the user is typing. Something like:

DispatcherTimer timer;
bool typing = false;
int seconds = 0;

public void TextBox_OnFocus(...)
{
  timer = new DispatcherTimer();
  timer.Interval = TimeSpan.FromSeconds(1);
  timer.Tick += new TickEventHandler(Timer_Tick);
  timer.Start();
}

public void TextBox_LostFocus(...)
{
  timer.Stop();
}

public void TextBox_OnKeyDown(...)
{
  typing = true;
}

public void Timer_Tick(...)
{
  if (!typing)
  { 
    seconds++;
  }
  else
  {
    seconds = 0;
  }
  if (seconds >= 3) SubmitData();
  typing = false;
}

I'm not sure this is the best approach (submitting data like this) but it should work. Note this is psuedo code only.

Upvotes: 4

Related Questions