Sabuncu
Sabuncu

Reputation: 5264

How to disable the default context menu for mouse right button in WPF RichTextBox?

I have the following event handler:

private void rtb_MouseDown(object sender, MouseEventArgs e)
{
    if (e.RightButton == MouseButtonState.Pressed)
    {
        // Get the nearest TextPointer to the mouse position. 
        TextPointer location = rtb.GetPositionFromPoint(Mouse.GetPosition(rtb), true);

        // Get the nearest word using this TextPointer. 
        TextRange word = GetWordRange(location);

        // Display the word. 
        tb.Text = word.Text;

        e.Handled = true;
    }
}

This is wired to the PreviewMouseDown event of a RichTextBox. This event fires and the above method is invoked, and the word under the cursor is displayed in a separate TextBox (called tb).

The problem is that, afterwards the default context menu (containing cut/copy/paste options) for the mouse right button click event is also displayed. Setting the Handled property to true does not seem to help. How can I have this context menu disabled?

EDIT: Xaml code:

<Window x:Class="rtbTest1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <RichTextBox Height="175" HorizontalAlignment="Left" Margin="10,127,0,0" Name="rtb" VerticalAlignment="Top" Width="483" PreviewMouseDown="rtb_MouseDown" />
        <TextBox Height="59" HorizontalAlignment="Left" Margin="286,24,0,0" Name="tb" VerticalAlignment="Top" Width="186" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="63,56,0,0" Name="btn1" VerticalAlignment="Top" Width="75" Click="btn1_Click" />
    </Grid>
</Window>

Upvotes: 1

Views: 9319

Answers (1)

brunnerh
brunnerh

Reputation: 184441

null it:

<RichTextBox ContextMenu="{x:Null}"/>

Upvotes: 15

Related Questions