【问题标题】:WPF EditingCommands Command BindingWPF EditingCommands 命令绑定
【发布时间】:2017-07-20 09:13:58
【问题描述】:

情况:

我在 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 方法上设置的断点

但是

当我点击粗体的切换按钮或按下 control + B 时,EditingCommand_Executed 没有被调试器击中(没有被执行)

我还尝试了什么:

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

【问题讨论】:

    标签: c# wpf commandbinding


    【解决方案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!");
            }
        }
    }
    

    【讨论】:

    • 不走运...正在执行命令但没有命中断点
    • 查看我的编辑。您可以使用 CommandManager.AddPreviewExecutedHandler 方法。
    • 我之前为 CommandExecuted 尝试过,为 PreviewExecuted 测试过 .... 仍然没有运气 .... 问题的另一部分是,我仍然可以管理按钮上的命令,但我真的很想处理快捷命令(Ctrl + B),用户肯定会使用
    • 你是说我的示例代码不起作用?它对我有用,所以请提供您问题的完整可编译示例。
    猜你喜欢
    • 2016-05-07
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多