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?
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.
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);
Use the DispatcherTimer class.