实时文本处理

时间:2013-05-03 07:57:32

标签: c# wpf textbox timeout

我有一个程序,可以将文本翻译成另一种语言。我希望通过这个小功能来改进它:文本在用户输入时实时翻译。

我写了这段代码:

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#...

3 个答案:

答案 0 :(得分:3)

您还可以考虑在找到“单词”完成后进行实际翻译,例如输入空格/制表符/输入键后,或文本框失去焦点等。

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

答案 1 :(得分:0)

您可以使用延迟绑定:

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

请注意,您应该设置一些具有名为Text的属性的类,并将INotifyPropertyChanged实现为DataContextWindowUserControl的{​​{1}} } 本身。

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

的示例

答案 2 :(得分:0)

我已将以下代码用于类似目的:

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方法将字符串分配给文本框(使用适当的调度程序进行线程同步)。

相关问题