tags:

views:

29

answers:

1

Using .NET 4 and VS2010 Pro, I've created a very simple WPF Application that contains the following XAML in the MainWindow:

<Grid>
    <RichTextBox x:Name="richTextBox" 
                 Margin="2"/>
</Grid>

All I would like to do, and have so far been unsuccessful at doing, is to replace the ContextMenu for the RichTextBox with my own. I've tried the code-behind from MSDN with no luck:

public MainWindow()
    {
        InitializeComponent();
        richTextBox.ContextMenuOpening += new ContextMenuEventHandler(richTextBox_ContextMenuOpening);
    }

    private void richTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
    {
        RichTextBox rtb = sender as RichTextBox;
        if (rtb == null)
        {
            return;
        }

        ContextMenu contextMenu = rtb.ContextMenu;
        contextMenu.Items.Clear();
        MenuItem menuItem = new MenuItem();
        menuItem.Header = "Test";
        contextMenu.Items.Add(menuItem);
        contextMenu.PlacementTarget = rtb;
        contextMenu.Placement = PlacementMode.RelativePoint;

        TextPointer position = rtb.Selection.End;

        if (position == null)
        {
            return;
        }

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

        contextMenu.IsOpen = true;
        e.Handled = true;
    }

I'm at a loss for what I'm not doing correctly. Does it have to with the MouseDown event being caught by the RTB? Do I have to derive my own version of the RTB and override ContextMenuOpening to get this to work? This seems like something really simple but I'm just not seeing it.

Thanks in advance.

A: 

Set the ContextMenu property on your RichTextBox to something other than null:

<RichTextBox x:Name="richTextBox" 
             Margin="2">
    <RichTextBox.ContextMenu>
        <ContextMenu/>
    </RichTextBox.ContextMenu>
</RichTextBox>

TextBoxBase, the base class of RichTextBox, has logic to automatically supply a context menu with things like Copy and Paste. This logic marks the ContextMenuOpening as handled, so your handler is not invoked. If you assign even an empty ContextMenu to your RichTextBox, it will leave your ContextMenu alone and invoke your handler.

Quartermeister