Silverlight Timer-Like Functionality

杀马特。学长 韩版系。学妹 提交于 2019-12-06 11:51:25

问题


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?


回答1:


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.




回答2:


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);



回答3:


Use the DispatcherTimer class.



来源:https://stackoverflow.com/questions/1850068/silverlight-timer-like-functionality

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