In WPF, the Textbox and RichTextBox controls have built-in spelling check attributes. However, this attribute currently only supports four languages by default: English, Spanish, French, and German.
· # LID 1033-English
· # LID 3082-Spanish
· # LID 1031-German
· # LID 1036-French
To use the spelling check function, you only need to set SpellCheck. IsEnabled to True.
<Grid> <TextBox SpellCheck.IsEnabled="True" /></Grid>
A red wavy line is displayed under a misspelled word. right-clicking the word will prompt you to correct the word.
The following example uses the SpellingError class to obtain the correct word to ListBox for your reference.
<StackPanel HorizontalAlignment="Center" Margin="20"> <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True"
MouseRightButtonUp="txtBox_MouseRightButtonUp" /> <ListBox x:Name="listBox" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox></StackPanel>
private void txtBox_MouseRightButtonUp(object sender, MouseButtonEventArgs e){ int catatPos = txtBox.CaretIndex; SpellingError error = txtBox.GetSpellingError(catatPos); if (error != null) { foreach (string suggession in error.Suggestions) { listBox.Items.Add(suggession); } }}
Right-click the wrong word and write the correct word to the list below.
In WPF 4, SpellCheck adds the CustomDictionaries function, which allows developers to add words that are not included or ignored in the default language for custom word spelling check. In the text entered in the previous example,MicrsoftVisualStvdio WPF4. In fact, we don't think "WPF" is a spelling mistake, but because the default four languages do not contain the word "WPF, therefore, you can use a custom dictionary to set "WPF" to recognize words.
Open the Notepad dictionary file (. lex) and write the word content in the file in the following format:
#LID 1033Word1Word2Word3
The first behavior dictionary in this document applies to the language type (English). If you do not write this line, it means it applies to all languages. For information about Locale ID in other languages, refer to here. In this example, we only need to write the "WPF" word in the document to add the edited dictionary file to the project:
Add a custom dictionary for TextBox:
<Window x:Class="WPFTextTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=System"> <StackPanel HorizontalAlignment="Center" Margin="20"> <TextBox x:Name="txtBox" SpellCheck.IsEnabled="True"> <SpellCheck.CustomDictionaries> <sys:Uri>pack://application:,,,/Lexicon/MSWord.lex</sys:Uri> </SpellCheck.CustomDictionaries> </TextBox> </StackPanel></Window>
The running program entered the same content. It can be seen that "WPF" is not identified as a spelling error: