How to: Modify, Add or Remove Items in Context Menu

  • 3 minutes to read

This example demonstrates how to customize the RichEditControl's context menu - remove the existing menu items and add new items.

Handle the RichEditControl.PopupMenuShowing event. Use the PopupMenuShowingEventArgs.MenuType property to determine the visual element for which the popup menu is invoked.

To remove a menu item, create the RemoveRichEditCommandAction object, set its ID to the ID of the command to remove and add that object to the PopupMenuShowingEventArgs.Customizations collection.

To add a new menu item, create a new BarButtonItem and add it to the PopupMenuShowingEventArgs.Customizations collection.

private void RichEditPopupMenuShowing(object sender, PopupMenuShowingEventArgs e) {
        if ((e.MenuType & RichEditMenuType.TableCell) != 0) {

        // Remove the unnecessary buit-in items by their indices.
        for (int i = e.Menu.Items.Count - 1; i >= 14; i--) {
                e.Menu.Items.RemoveAt(i);
        }

        // Remove the "Cut" and "Copy" menu items.
        e.Customizations.Add(new RemoveRichEditCommandAction() { Id = RichEditCommandId.CutSelection});
        e.Customizations.Add(new RemoveRichEditCommandAction() { Id = RichEditCommandId.CopySelection });
        // Create a menu item for the RichEdit command, which invokes the Insert Picture dialog.
        e.Customizations.Add(new BarButtonItem() {
            Command = RichEditUICommand.InsertPicture,
            Content = "Insert Picture",
            CommandParameter = richEdit
        });

        // Create a custom menu item and handle its click event.
        BarButtonItem menuItem = new BarButtonItem();
        menuItem.Name = "customHighlightItem";
        menuItem.Content = "Highlight Selection";
        menuItem.ItemClick += new ItemClickEventHandler(customHighlightItem_ItemClick);
        e.Customizations.Add(menuItem);
    }
}

private void customHighlightItem_ItemClick(object sender, ItemClickEventArgs e) {
    CharacterProperties charProps = richEdit.Document.BeginUpdateCharacters(richEdit.Document.Selection);
    charProps.BackColor = System.Drawing.Color.Yellow;
    richEdit.Document.EndUpdateCharacters(charProps);
}