I'd like to add a menu item to the default ContextMenu of a RichTextBox. I can create a new context menu but then I loose the spell check suggestions that show up in the default menu. Is there a way to add an item without re-implementing everything?
+6
A:
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.
Donnelle
2008-10-17 03:07:32
Thanks, Donnelle. I figured it would probably come to re-implementing. Thanks for the tips on how to do this!
dmo
2008-10-20 18:44:49