add menu item to default context menu

試著忘記壹切 提交于 2020-01-20 03:26:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/210634/add-menu-item-to-default-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!