Prevent Spelling Mistakes in Your WPF Applications | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Prevent Spelling Mistakes in Your WPF Applications

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
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 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
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
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
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
    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
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!

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed