Search code examples
c#.netwpf.net-4.6.1

AutoCorrect in WPF Richtextbox


I read on MSDN that .NET 4.6.1 supports auto correct now. The files in %appdata%/Microsoft/Spelling// were created automatically and I added the following line to the default.acl (file is still UTF-16 with BOM):

tramampoline|trampoline

I have set the project to target 4.6.1 and enabled SpellCheck on a RichTextBox:

<RichTextBox SpellCheck.IsEnabled="True" Language="de-DE"/>

While it highlights the word when typed wrong in the usual manner, there is no autocorrection happening.

What am I missing here? I don't quite understand the note:

Note: These new file-formats are not directly supported by the WPF spell checking API’s, and the custom dictionaries supplied to WPF in applications should continue to use .lex files.


Solution

  • I know this is old, but as far as I know you need to handle AutoCorrect on your own (if I'm wrong please correct me with an example). You can do this as follows:

    var caretPosition = richTextBox.CaretPosition;
    // Make sure you're passing a textpointer at the end of the word you want to correct, i.e. not like this ;)
    errorPosition = richTextBox.GetNextSpellingErrorPosition(caretPosition, LogicalDirection.Backward);
    if(errorPosition == null)
    {
        return;
    }
    
    var errors = richTextBox.GetSpellingError(errorPosition);
    // Default would be to only replace the text if there is one available replacement
    // but you can also measure which one is most likely with a simple string comparison
    // algorithm, e.g. Levenshtein distance
    if (errors.Suggestions.Count() == 1) 
    {
        var incorrectTextRange = richTextBox.GetSpellingErrorRange(errorPosition);
        var correctText = error.Suggestions.First();
        var incorrectText = incorrectTextRange.Text;
    
        // Correct the text with the chosen word...
        errors.Correct(correctText);
    }
    
    // Set caret position...
    

    An important note would be not to use the RTB's CaretPosition, but rather to use a textpointer at the end of the word you wish to correct. If your textpointer/caret is in a weird spot (e.g. the end of 20 whitespaces), the GetNextSpellingErrorPosition method may take up to 60 seconds before it returns (depending on the hardware/number of words in your RTB).