实时文本处理

实时文本处理

问题描述:

我有一个程序,将文本翻译成另一种语言。我想通过这个小功能来改进它:当用户输入文本时,文本会实时翻译。实时文本处理

我写了这个代码:

private void TextBox_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e) 
{ 
    TranslateBox.Text = translate.translateText(TextToTranslate.Text, "eng", "es"); 
} 

它的工作原理,但在我输入的 “Hello World”,这个函数会被调用11次。这是一个很大的负担。 有什么办法可以设置这个功能的超时时间吗?

PS。我知道它是如何做的JS,而不是在C#...

+0

WPF或winforms? – 2kay 2013-05-03 08:04:54

+0

我用这个应用程序的WPF。 – 2013-05-03 08:06:08

您可以使用延迟绑定:

<TextBox Text="{Binding Path=Text, Delay=500, Mode=TwoWay}"/> 

请注意,您应该设置一些类,它具有财产称为Text和农具INotifyPropertyChangedDataContextWindowUserControlTextBox 本身。在MSDN

例子:http://msdn.microsoft.com/en-us/library/ms229614.aspx

我用下面的代码类似用途:

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

.. 。其中SetText方法将字符串分配给文本框(使用适当的分派器进行线程同步)。

你也可以考虑做实际的翻译,当你发现一个“字”结束后,如空间/制表后/确定键被输入,或者当文本框losts集中等

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