wpf-400620-controls-and-libraries-spell-checker-examples-how-to-add-spell-check-menu-items-to-the-standard-text-controls.md
The following code example shows how to add spell check items for the .NET RichTextBox control’s context menu.
Create a new MenuItems property in code-behind and bind it to the RichTextBox’s ContextMenu property in XAML, as shown below:
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
public ObservableCollection<object> MenuItems { get; } = new ObservableCollection<object>();
Public Sub New()
DataContext = Me
InitializeComponent()
End Sub
Public ReadOnly Property MenuItems As ObservableCollection(Of Object) = New ObservableCollection(Of Object)()
<RichTextBox x:Name="richTextBox">
<RichTextBox.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=MenuItems}"/>
</RichTextBox.ContextMenu>
</RichTextBox>
Add the SpellChecker behavior to the RichTextBox in XAML. Refer to the Configure Spell-Checking Behavior lesson for more information about the SpellChecker behavior and an example on how to add dictionaries.
<RichTextBox x:Name="richTextBox">
<RichTextBox.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=MenuItems}"/>
</RichTextBox.ContextMenu>
<dxmvvm:Interaction.Behaviors>
<dxspch:DXSpellChecker Culture="en-US" CheckAsYouType="True"/>
</dxmvvm:Interaction.Behaviors>
</RichTextBox>
Call the GetErrorOperationCommands method to obtain a list of available commands and assign it to the MenuItems property in the PreviewMouseRightButtonUp event handler. The SpellCheckerCommand.DoCommand method executes the retrieved command.
void RichTextBox_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
MenuItems.Clear();
var commands = this.richTextBox.GetErrorOperationCommands(e.GetPosition(this.richTextBox));
foreach (var command in commands)
{
var menuItem = new MenuItem();
menuItem.Header = command.Caption;
menuItem.Click += (s, args) => command.DoCommand();
menuItem.IsEnabled = command.Enabled;
MenuItems.Add(menuItem);
}
if (MenuItems.Count == 0)
MenuItems.Add(new MenuItem() { Header = "No Error", IsEnabled = false });
}
Private Sub RichTextBox_PreviewMouseRightButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
MenuItems.Clear()
Dim commands = Me.richTextBox.GetErrorOperationCommands(e.GetPosition(Me.richTextBox))
For Each command In commands
Dim menuItem = New MenuItem()
menuItem.Header = command.Caption
AddHandler menuItem.Click, Sub(s, args) command.DoCommand()
menuItem.IsEnabled = command.Enabled
MenuItems.Add(menuItem)
Next command
If MenuItems.Count = 0 Then
MenuItems.Add(New MenuItem() With {.Header = "No Error", .IsEnabled = False})
End If
End Sub
<RichTextBox x:Name="richTextBox" PreviewMouseRightButtonUp="RichTextBox_PreviewMouseRightButtonUp">
...
</RichTextBox>