Question

I'd like to add a menu item to the default ContextMenu of a RichTextBox.

I could create a new context menu but then I lose the spell check suggestions that show up in the default menu.

Is there a way to add an item without re-implementing everything?

Was it helpful?

Solution

It's not too tricky to reimplement the RichTextBox context menu with spelling suggestions, Cut, Paste, etc.

Hook up the context menu opening event as follows:

AddHandler(RichTextBox.ContextMenuOpeningEvent, new ContextMenuEventHandler(RichTextBox_ContextMenuOpening), true);

Within the event handler build the context menu as you need. You can recreate the existing context menu menu items with the following:

private IList<MenuItem> GetSpellingSuggestions()
{
    List<MenuItem> spellingSuggestions = new List();
    SpellingError spellingError = myRichTextBox.GetSpellingError(myRichTextBox.CaretPosition);
    if (spellingError != null)
    {
        foreach (string str in spellingError.Suggestions)
        {
            MenuItem mi = new MenuItem();
            mi.Header = str;
            mi.FontWeight = FontWeights.Bold;
            mi.Command = EditingCommands.CorrectSpellingError;
            mi.CommandParameter = str;
            mi.CommandTarget = myRichTextBox;
            spellingSuggestions.Add(mi);
        }
    }
    return spellingSuggestions;
}

private IList<MenuItem> GetStandardCommands()
{
    List<MenuItem> standardCommands = new List();

    MenuItem item = new MenuItem();
    item.Command = ApplicationCommands.Cut;
    standardCommands.Add(item);

    item = new MenuItem();
    item.Command = ApplicationCommands.Copy;
    standardCommands.Add(item);

    item = new MenuItem();
    item.Command = ApplicationCommands.Paste;
    standardCommands.Add(item);

    return standardCommands;
}

If there are spelling errors, you can create Ignore All with:

MenuItem ignoreAllMI = new MenuItem();
ignoreAllMI.Header = "Ignore All";
ignoreAllMI.Command = EditingCommands.IgnoreSpellingError;
ignoreAllMI.CommandTarget = textBox;
newContextMenu.Items.Add(ignoreAllMI);

Add separators as required. Add those to the new context menu's items, and then add your shiny new MenuItems.

I'm going to keep looking for a way to obtain the actual context menu though, as this is relevant to something I'll be working on in the near future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top