Silverlight Timer-Like Functionality

随声附和 提交于 2019-12-04 17:51:36

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!