2012-01-08 118 views
1

我有以下事件处理程序:如何在WPF RichTextBox中禁用鼠标右键的默认上下文菜单?

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; 
    } 
} 

这是连接到一个RichTextBox的PreviewMouseDown事件。此事件触发并调用上述方法,光标下的单词显示在单独的文本框(称为tb)中。

的问题是,事后默认的上下文菜单(含剪切/复制/粘贴选项)为鼠标右键单击事件也被显示。将Handled属性设置为true似乎没有帮助。我怎样才能禁用此上下文菜单?

编辑:XAML代码:

<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> 
+2

请添加XAML代码以及 – Mharlin 2012-01-08 20:59:29

回答

10

null它:

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

是的,这工作,谢谢。我不明白的是:这不会禁用RichTextBox的* all *上下文菜单吗?此外,这是应该怎么做,或者这是一个蛮力解决方案? – Sabuncu 2012-01-08 21:26:15

+0

@Sabuncu:有多个上下文菜单?如果你想要另一个上下文菜单,但不要将它设置为空,而是将其设置为你想要的上下文菜单,这里没有任何关于这方面的远程蛮力。 – 2012-01-08 21:39:57

+0

显示已剪切/复制/粘贴的上下文菜单,因为某些事件处理程序上游被触发。为什么即使我在我的事件处理程序代码中将Handled设置为true? – Sabuncu 2012-01-09 06:11:52

相关问题