自定义词典的Wpf Textbox拼写检查问题

时间:2014-05-12 09:58:04

标签: wpf textbox spell-checking

我在Wpf应用程序中对自定义词典进行了拼写检查,因为它无法识别IΔn。

如果我添加一个行为来尝试和处理IΔn,DoSpellCheck()在您键入或粘贴文本到文本框时起作用,但在调用textBox_Loaded(对象发送者,RoutedEventArgs e)时不起作用。

任何帮助都会受到赞赏。

public class TextBoxExtendedSpellCheckBehavior:Behavior     {         private static Key [] _nonInputKeys = new Key [] {Key.Left,Key.Up,Key.Right,Key.Down,Key.Tab,Key.Delete,Key.Back,Key.Escape,Key.Enter}; < / p>

    protected override void OnAttached()
    {
        if (AssociatedObject is TextBox)
        {
            TextBox textBox = AssociatedObject as TextBox;
            textBox.PreviewKeyUp += OnTextBox_PreviewKeyUp;
            textBox.LostFocus += OnTextBox_LostFocus;
            textBox.TextChanged += OnTextChanged;
            textBox.Loaded += textBox_Loaded;


        }
        base.OnAttached();
    }

    void textBox_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            DoSpellCheck(textBox);
        }

    }

    protected override void OnDetaching()
    {
        if (AssociatedObject is TextBox)
        {
            TextBox textBox = AssociatedObject as TextBox;
            textBox.PreviewKeyUp -= OnTextBox_PreviewKeyUp;
            textBox.LostFocus -= OnTextBox_LostFocus;
            textBox.Loaded -= textBox_Loaded;
        }
        base.OnDetaching();
    }

    private static void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        if (sender is TextBox)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null && textBox.IsLoaded == true)
            {
                DoSpellCheck(textBox);
            }

        }
    }

    private bool IsInputKey(Key key)
    {
        return !_nonInputKeys.Contains(key);
    }

    private void OnTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (sender is TextBox && IsInputKey(e.Key))
        {
            TextBox textBox = sender as TextBox;

            DoSpellCheck(textBox);
        }
    }

    private void OnTextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox)
        {
            TextBox textBox = sender as TextBox;
            DoSpellCheck(textBox);
        }

    }

    public static void DoSpellCheck(TextBox textBox)
    {
        const string iDelta = "I∆n";

        int index = textBox.Text.IndexOf(iDelta);
        if (index > 0)
        {
            int iStart = textBox.GetSpellingErrorStart(index);
            if (iStart > -1)
            {
                SpellingError spellingError = textBox.GetSpellingError(iStart);
                if (spellingError != null)
                {
                    spellingError.IgnoreAll();
                }
            }
        }

    }
}

0 个答案:

没有答案
相关问题