如何:在 RichTextBox 中定位自定义上下文菜单

更新:2007 年 11 月

本示例演示如何定位 RichTextBox 的自定义上下文菜单。

实现 RichTextBox 的自定义上下文菜单时,应负责处理上下文菜单的定位。 默认情况下,自定义上下文菜单是在 RichTextBox 中心打开的。

有关对此示例进行演示的有效示例,请参见在 RichTextBox 中定位自定义上下文菜单的示例

示例

若要重写默认定位行为,应当为 ContextMenuOpening 事件添加一个侦听器。 下面的示例演示如何以编程方式实现此目的。

richTextBox.ContextMenuOpening += new ContextMenuEventHandler(richTextBox_ContextMenuOpening);

下面的示例演示对应 ContextMenuOpening 事件侦听器的实现。

// This method is intended to listen for the ContextMenuOpening event from a RichTextBox.
// It will position the custom context menu at the end of the current selection.
void richTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    // Sender must be RichTextBox.
    RichTextBox rtb = sender as RichTextBox;
    if (rtb == null) return;

    ContextMenu contextMenu = rtb.ContextMenu;
    contextMenu.PlacementTarget = rtb;

    // This uses HorizontalOffset and VerticalOffset properties to position the menu,
    // relative to the upper left corner of the parent element (RichTextBox in this case).
    contextMenu.Placement = PlacementMode.RelativePoint;

    // Compute horizontal and vertical offsets to place the menu relative to selection end.
    TextPointer position = rtb.Selection.End;

    if (position == null) return;

    Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);
    contextMenu.HorizontalOffset = positionRect.X;
    contextMenu.VerticalOffset = positionRect.Y;

    // Finally, mark the event has handled.
    contextMenu.IsOpen = true;
    e.Handled = true;
}

请参见

概念

RichTextBox 概述

TextBox 概述