2016-05-13 36 views
0

RichTextBox提供lot of commands以及伴隨的鍵手勢。如何使RichTextBox停止使用鍵手勢

但是,當設置了IsReadOnly=True時,其中很多命令沒有意義,也不會採取任何措施。 Ctrl + ICtrl + R

<Window x:Class="MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:" 
     mc:Ignorable="d"> 
<Window.CommandBindings> 
    <CommandBinding Command="local:MainWindow.MyCommand" Executed="MyCommandBinding_Executed" /> 
</Window.CommandBindings> 
<StackPanel> 
    <RichTextBox Height="50" IsReadOnly="True" /> 
    <CheckBox Content="This is a checkbox" /> 
    <TextBlock Name="whatsGoingOn" /> 
</StackPanel> 
</Window> 

 

using System.Windows; 
using System.Windows.Input; 

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    public static RoutedUICommand MyCommand = new RoutedUICommand(
     "My Command", 
     "MyCommand", 
     typeof(MainWindow), 
     new InputGestureCollection() { new KeyGesture(Key.R, ModifierKeys.Control) }); 

    private void MyCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
    { 
     whatsGoingOn.Text += "."; 
    } 
} 

現在也許正確的答案是:然而,當在窗口中的命令使用密鑰的手勢之一,在窗口中的命令不會當RichtTextBox有集中火力「不要使用RichTextBox與IsReadOnly="True",而是使用別的東西」,但讓我們假設我必須或想使用RichTextBox。

即使RichTextBox具有焦點,我可以做什麼來使關鍵手勢激發我的命令?

回答

0

您可以截取RichTextBox的PreviewKeyDown事件中的擊鍵。將e.Handled成員設置爲true,這將阻止實際處理密鑰。

希望它有幫助

+0

在派生類中攔截PreviewKeyDown或重寫OnPreviewKeyDown不會使命令觸發。當然,我可以手動調用'MyCommand_Executed',但是我不需要首先使用命令。此外,以這種方式攔截一個關鍵筆劃對於在這個問題中提到的原因有點冒失:https://stackoverflow.com/questions/12125590/how-to-correctly-retrieve-modifier-keys-in-a-wpf- KEYDOWN事件。對不起,但我不相信:) – Martin