Copied RSS Feed

WPF

Prevent Spelling Mistakes in Your WPF Applications

Syncfusion WPF SpellChecker control helps you detect spelling mistakes in your application and fix them. It has a built-in dictionary for English. However, you can also check the spelling of text in other languages by integrating dictionary files in standard formats such as Hunspell, Ispell, and OpenOffice.

You can also add custom words that are not available in the dictionary file by using the custom dictionary. You can even add multiple dictionaries specific to different cultures, and switch between them at runtime.

SpellChecker also provides intuitive ways to fix spelling mistakes by listing suggestions in a context menu and dialog box, similar to Microsoft Office applications.

Let’s proceed with using the Syncfusion WPF SpellChecker to check the spelling of text in a text editor control.

Configuring SpellChecker in a text editor control

Follow these steps to configure SpellChecker in a text editor control:

Step 1: Create the project

Create a new WPF project in Visual Studio.

Step 2: Add the control manually using code

To add the Spell Checker manually in C#, follow these steps:

  1. Install the Syncfusion.SfSpellChecker.WPF NuGet package in your project.
  2. Include the namespace Syncfusion.Windows.Controls by using the following code.
    using Syncfusion.Windows.Controls;
    
  3. Create an instance of the SpellChecker control by using the following code.
    SfSpellChecker SpellChecker = new SfSpellChecker();
    

Let’s design a view with TextBox and Button controls. Here, we are going to perform a spell checking in the TextBox  control when a button is clicked.

Step 3: Configure the SfSpellChecker to the text editor

  1. Create a class implementing the IEditorProperties interface which acts as a bridge between the editor and the SpellChecker control. Refer to the following code. Here, I am naming the class TextSpellEditor.
    //Creating TextSpell Editor 
    public class TextSpellEditor : IEditorProperties
    {
       /// <summary> 
       /// Initializes the TextBox control. 
       /// </summary> 
       private TextBox textbox;
    
       /// <summary> 
       /// Gets or sets the control whose text is to be spell checked. 
       /// </summary> 
       public Control ControlToSpellCheck 
       { 
          get {
                return textbox; 
          } 
          set {
                textbox = value as TextBox; 
          } 
       } 
    
       /// <summary> 
       /// Initializes the new instance of the TextSpellEditor class. 
       /// </summary> 
       /// <param name="control"></param> 
       public TextSpellEditor(Control control) 
       { 
          ControlToSpellCheck = control;
       }
    
       /// <summary> 
       /// Gets or sets the current misspelled word. 
       /// </summary> 
       public string SelectedText 
       { 
          get { 
                return textbox.SelectedText; 
          }
          set { 
                textbox.SelectedText = value; 
          } 
       }
    
       /// <summary> 
       /// Gets or sets the text to be spell checked by the SfSpellChecker. 
       /// </summary>
       public string Text
       { 
          get { 
                return textbox.Text;
          }
          set
          { 
             textbox.Text = value;
          } 
       }
    
       /// <summary> 
       /// Selects the word specified by the index.
       /// </summary> 
       /// <param name="selectionStart">Zero-based index of the word in the text.</param> 
       /// <param name="selectionLength">length of the word to be selected.</param> 
       public void Select(int selectionStart, int selectionLength)
       {
          textbox.Select(selectionStart, selectionLength); 
       }
    
       public bool HasMoreTextToCheck()
       { 
          return false; 
       }
    
       public void Focus()
       {
          textbox.Focus();
       } 
    
       public void UpdateTextField() 
       {
          throw new NotImplementedException();
       }
    }
  2. Create and add the instance of TextBox (the editor control to be spell checked) and Button to the window as shown in the following code example.
    <Grid VerticalAlignment="Center">
        <StackPanel> 
            <TextBox Text="Natusre is an importsant and integral part of mankind. It is one of the greattest blessings for human lifve. Howeverq, nowadays humans fail to recognize it as one. Nature has been an inspiration for numerous poets, writeqrs, artists and more of yesteryears." 
                     Name="textbox" 
                     TextWrapping="Wrap" 
                     VerticalContentAlignment="Top"/>
            <Button HorizontalAlignment="Center" 
                    Content="Spell Check" 
                    Click="SpellCheck_ButtonClick"/>
        </StackPanel>
    </Grid>
    

Now, we have integrated the WPF SpellChecker into the text editor control. It should look like the following screenshot.

Text Editor Control with WPF SpellChecker

Perform spell check

As state previously, you can perform spell checking and suggest appropriate spellings by using a context menu or a dialog box. The following sections describe how to implement these features.

Spell check through context menu

Create an instance of the TextSpellEditor class by passing the TextBox instance as a parameter to its constructor. Then, add the instance of TextSpellEditor to the SpellChecker by using the PerformSpellCheckUsingContextMenu method.

TextSpellEditor SpellEditor = new TextSpellEditor(txtbx);

//Enable context menu for SpellChecker
SpellChecker.PerformSpellCheckUsingContextMenu(SpellEditor);
Spell Checking via Context Menu

Spell check through dialog box

Alternatively, you can perform the spell check using a dialog box by calling the PerformSpellCheckUsingDialog method.

private void SpellCheck_ButtonClick(object sender, EventArgs e) 
{
  SpellChecker.PerformSpellCheckUsingDialog(new TextSpellEditor(txtbx));
}

Executing the project will result in output like the following screenshot.

Spell Checking via Dialog Box

Load your own dictionaries for any language

You can also add your own dictionary to the SfSpellChecker.Dictionaries collection.

The SpellChecker control supports the following standard dictionary file formats:

  • Hunspell
  • Ispell
  • OpenOffice

SpellCheck using a Hunspell dictionary

You can check for spelling mistakes using the Hunspell dictionary format. This format contains the following files:

  • Affix file with grammar rules: *.aff
  • Basic words file: *.dic file.

Note: You can get different languages for Hunspell dictionaries in this GitHub location.

Follow these steps to spell check using a Hunspell dictionary.

Adding a Hunspell dictionary requires adding *.aff and *.dic culture files as a Resource to the application. Here, we are going to add the Hunspell dictionary for the French culture. Refer to the following screenshot.

French Culture Files
  1. Create an instance of the HunspellDictionary and add the basic word and grammar file path to the HunspellDictionary.DictionaryUri and HunspellDictionary.GrammarUri
    properties. Add the culture to the HunspellDictionary.Culture property.
  2. Add the HunspellDictionary to the SfSpellChecker.Dictionaries collection.
  3. Then, set the required culture to the SfSpellChecker.Culture property.

Refer to the following code.

//Creating a culture instance 
CultureInfo culture = new CultureInfo("fr-FR");
SfSpellChecker SpellChecker = new SfSpellChecker();

// Adding Hunspell dictionaries in Dictionaries collection 
SpellChecker.Dictionaries = new DictionaryCollection(); 

//Add French culture Hunspell dictionary 
SpellChecker.Dictionaries.Add( 
    new HunspellDictionary()
    { 
        Culture = culture,
        GrammarUri = new Uri("/HunSpellCheck;component//French/fr-FR.aff", 
                            UriKind.Relative), 
        DictionaryUri = new Uri("/HunSpellCheck;component//French/fr-FR.dic",
                                  UriKind.Relative) 
    }); 

//Setting a French culture for SpellChecker 
SpellChecker.Culture = culture;

In a similar way, you can also add and set the culture for Ispell and OpenOffice dictionaries. Refer to this documentation for more information.

You can get different languages for the Ispell and OpenOffice dictionaries from the following locations:

Switching language (culture) at runtime

The SpellChecker control allows you to add multiple dictionaries for unique cultures into the SfSpellChecker.Dictionaries collection.

You can set one of the cultures at runtime by changing the SfSpellChecker.Culture property. Based on the value of SfSpellChecker.Culture, the respective dictionary will be used for spell checking the text.
Refer to the following code example.

//Creating a culture instance 
CultureInfo culture = new CultureInfo("fr-FR");
SfSpellChecker SpellChecker = new SfSpellChecker();

// Adding Hunspell dictionaries in Dictionaries collection 
SpellChecker.Dictionaries = new DictionaryCollection();

//Add French culture Hunspell dictionary 
SpellChecker.Dictionaries.Add( 
    new HunspellDictionary()
    { 
        Culture = culture, 
        GrammarUri = new Uri("/HunSpellCheck;component//French/fr-FR.aff", 
                              UriKind.Relative),
        DictionaryUri = new Uri("/HunSpellCheck;component//French/fr-FR.dic", 
                                 UriKind.Relative) 
    }); 

//Add Spanish culture Hunspell dictionary 
SpellChecker.Dictionaries.Add( 
    new HunspellDictionary()
    { 
        Culture = new CultureInfo("es-ES"),
        GrammarUri = new Uri("/HunSpellCheck;component//Spanish/es-ES.aff", 
                              UriKind.Relative), 
        DictionaryUri = new Uri("/HunSpellCheck;component//Spanish/es-ES.dic", 
                                 UriKind.Relative) 
    }); 

//Add US culture Hunspell dictionary 
SpellChecker.Dictionaries.Add( 
    new HunspellDictionary() 
    { 
        Culture = new CultureInfo("en-US"), 
        GrammarUri = new Uri("/HunSpellCheck;component//US/en-US.aff", 
                              UriKind.Relative), 
        DictionaryUri = new Uri("/HunSpellCheck;component//US/en-US.dic", 
                                 UriKind.Relative) 
    });

//Setting a French culture for SpellChecker 
SpellChecker.Culture = culture;

Here, SfSpellChecker.Culture is set to fr-FR. So, the dictionary for the fr-FR culture will be used as the spell check dictionary.
Refer to the following screenshot.

Spell Check with French Dictionary

Add words to dictionary

You can add custom words that are not available in an existing dictionary. Add the words to the  SfSpellChecker.Dictionaries collection using the CustomDictionary class. This custom dictionary does not have a grammar file; it accepts only the dictionary files that contain a list of words.

You can also add words to this custom dictionary by clicking on the Add to Dictionary button available in the SpellChecker dialog box or context menu.

You can also add multiple CustomDictionary classes for each culture using the SfSpellChecker.Dictionaries collection.

For example, if you load the SfSpellChecker with the en-US culture, then you can add custom words only to the en-US culture CustomDictionary. The following steps explain how to do so:

  1. Create a custom dictionary text file, set the Build Action as None, and set Copy to Output Directory to Copy if newer as shown in the following screenshot.

    Adding Custom Dictionary File

  2. Create a CutomDictionary instance, add the custom word file path to the CustomDictionary.DictionaryUri property, and add the culture to the CustomDictionary.Culture property.
  3. Add the CutomDictionary into the SfSpellChecker.Dictionaries collection.
    Refer to the following code example.
    //Creating a culture instance 
    CultureInfo culture = new CultureInfo("en-US");
    SfSpellChecker SpellChecker = new SfSpellChecker(); 
    
    // Get the location of the dictionary file
    Uri CustomDict_uri= new Uri(Directory.GetCurrentDirectory()+ 
                                @"\English\Custom_en-US.txt", UriKind.Absolute);
    
    // Creating instance for the Dictionaries collection 
    SpellChecker.Dictionaries = new DictionaryCollection();
    
    //Add custom dictionary for US culture 
    SpellChecker.Dictionaries.Add(
       new CustomDictionary() 
       {
          Culture = culture,
          DictionaryUri = CustomDict_uri 
       });
Adding Words to Custom Dictionary

Conclusion

I hope you now have a clear idea about what is needed to add the WPF SpellChecker control to a text editor control. With its features, you can dynamically perform spelling checks for text of any language and culture and add custom words to its dictionary too. Try the control in your application and tell us your impressions in the comment section below.

The Syncfusion WPF UI controls package includes over 95 essential WPF controls like DataGrid, Charts, DiagramPDF Viewer, and more for building powerful line-of-business Windows applications faster. Use them to boost your productivity!

For current Syncfusion customers, the newest version is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out the available features. You can also try our samples at this GitHub location, and live demos are available in here.

You can always contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Meet the Author

Prabakaran Sangameswaran

Prabakaran Sangameswaran is a software developer at Syncfusion Software. He has experience in the development of Window Forms and WPF controls. He is interested in learning new computer applications and related technology.