我有一个程序,把文字翻译成另一种语言。我想用这个小功能来改进它:当用户输入文本时,文本会实时翻译。
我写了这段代码:
private void TextBox_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
{
TranslateBox.Text = translate.translateText(TextToTranslate.Text, "eng", "es");
}它可以工作,但是当我输入"Hello“时,这个函数将被调用11次。这是个很大的负担。有任何方法来设置这个函数的超时吗?
PS。我知道JS的情况,但C#不知道.
发布于 2013-05-03 08:04:06
您可以使用延迟绑定:
<TextBox Text="{Binding Path=Text, Delay=500, Mode=TwoWay}"/>请注意,您应该设置一些类,该类具有名为Text的属性,并将INotifyPropertyChanged实现为Window的DataContext或UserControl或TextBox本身。
msdn上的示例:http://msdn.microsoft.com/en-us/library/ms229614.aspx
发布于 2013-05-03 08:24:54
当您发现一个"word“已经完成时,您也可以考虑进行实际的翻译,例如在输入空格/tab/enter键之后,或者textbox丢失焦点等。
private void TextBox_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
{
if(...) // Here fill in your condition
TranslateBox.Text = translate.translateText(TextToTranslate.Text, "eng", "es");
}发布于 2013-05-03 08:05:19
为了类似的目的,我使用了以下代码:
private readonly ConcurrentDictionary<string, Timer> _delayedActionTimers = new ConcurrentDictionary<string, Timer>();
private static readonly TimeSpan _noPeriodicSignaling = TimeSpan.FromMilliseconds(-1);
public void DelayedAction(Action delayedAction, string key, TimeSpan actionDelayTime)
{
Func<Action, Timer> timerFactory = action =>
{
var timer = new Timer(state =>
{
var t = state as Timer;
if (t != null) t.Dispose();
action();
});
timer.Change(actionDelayTime, _noPeriodicSignaling);
return timer;
};
_delayedActionTimers.AddOrUpdate(key, s => timerFactory(delayedAction),
(s, timer) =>
{
timer.Dispose();
return timerFactory(delayedAction);
});
}在您的情况下,您可以这样使用它:
DelayedAction(() =>
SetText(translate.translateText(TextToTranslate.Text, "eng", "es")),
"Translate",
TimeSpan.FromMilliseconds(250));...where -- SetText方法将将字符串分配给textbox (使用适当的调度程序进行线程同步)。
https://stackoverflow.com/questions/16354118
复制相似问题