WPF EditingCommands命令绑定

时间:2017-07-20 09:13:58

标签: c# wpf commandbinding

情况:

我在WPF窗口中有一些编辑命令,还有一个关闭命令(Application.CloseCommand)并且有一些像这样的绑定

查看:

 <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandBinding_Executed"/>
        <CommandBinding Command="EditingCommands.ToggleBold"
                        Executed="EditingCommand_Executed"></CommandBinding>
 </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="Esc" Command="ApplicationCommands.Close"></KeyBinding>
    </Window.InputBindings>
.. *Some panel and grid stuff and more things* ..
<RichTextBox Name="RTBPopup">
       <RichTextBox.InputBindings>
            <KeyBinding Key="Esc" Command="ApplicationCommands.Close"></KeyBinding>
       </RichTextBox.InputBindings>
</RichTextBox>
.. *Some panel and grid stuff and more things* ..
<ToggleButton x:Name="btnToggleBold" CommandManager.Executed="EditingCommand_Executed" Command="EditingCommands.ToggleBold" CommandTarget="{Binding ElementName=RTBPopup}">B</ToggleButton>

现在:

如果我在RTBPopup(Richtextbox)中按下escape,命令将被执行,调试器将点击CloseCommandBinding_Executed方法

上设置的断点

当我点击切换按钮以显示粗体或按下控制键+ B时,EditingCommand_Executed未被调试器命中(未执行)

我还尝试了什么:

 <ToggleButton.CommandBindings>
      <CommandBinding Command="EditingCommands.ToggleBold" Executed="EditingCommand_Executed"></CommandBinding>
 </ToggleButton.CommandBindings>

1 个答案:

答案 0 :(得分:1)

处理PreviewExecuted事件:

<CommandBinding Command="EditingCommands.ToggleBold" 
                PreviewExecuted="CommandBinding_PreviewExecuted" />

该命令由RichTextBox处理,因此它永远不会冒泡到您的父Window

您还可以尝试使用CommandManager以编程方式挂钩事件处理程序:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        CommandManager.AddPreviewExecutedHandler(RTBPopup, new ExecutedRoutedEventHandler(OnExecuted));
    }

    private void OnExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        if(e.Command == EditingCommands.ToggleBold)
        {
            MessageBox.Show("fired!");
        }
    }
}