【问题标题】:WPF Routed Command only fires sometimesWPF 路由命令有时只会触发
【发布时间】:2011-02-24 21:42:32
【问题描述】:

我有一些 RoutedCommands 用于控制-A、复制粘贴等命令,它们都可以正常工作。 然后我添加了 4 个路由命令来使用箭头键在画布中左右上下移动对象,它们有时有效,有时无效。起初我认为这是画布上的焦点问题,但我发现同时,所有其他路由命令(如 control-A)都有效,但箭头键无效。 我真的不知道这里发生了什么,它们是具有不同变量名称的相同路由命令,为什么一个工作 100% 的时间,一个只工作 50% 的时间?

工作路由命令:

_bindings.Add(new CommandBinding(DesignerCanvas.SelectAll, SelectAll_Executed));
SelectAll.InputGestures.Add(new KeyGesture(Key.A, ModifierKeys.Control));

private void SelectAll_Executed(object sender, ExecutedRoutedEventArgs e)
{
    SelectionService.SelectAll();
}

RoutedCommand 故障:

_bindings.Add(new CommandBinding(DesignerCanvas.MoveDown, MoveDown_Executed));
MoveDown.InputGestures.Add(new KeyGesture(Key.Down));

private void MoveDown_Executed(object sender, ExecutedRoutedEventArgs e)
{
    e.Handled = true;
    var selectedItems = from item in SelectionService.CurrentSelection.OfType<DesignerItem>()
                            select item;

    if (selectedItems.Count() > 0)
    {
        for (int i = 0; i < selectedItems.Count(); i++)
            selectedItems.ElementAt(i).Top += Option.OptionSingleton.Sensitivity;
    }
}

有故障的 RoutedCommand 有时只是不触发,尤其是在我打开其他窗口并返回画布后,它会停止触发,而其他路由命令不受影响。任何想法是什么导致了这种奇怪的行为?

【问题讨论】:

    标签: wpf canvas focus routedcommand


    【解决方案1】:

    您有时可以使用非常包容的类事件处理程序来跟踪事件的路径:

    EventManager.RegisterClassHandler(typeof(FrameworkElement), CommandManager.CanExecuteEvent, 
         new CanExecuteRoutedEventHandler((s, e) => Debug.WriteLine("CanExecute: " + s)), true);
    EventManager.RegisterClassHandler(typeof(FrameworkElement), CommandManager.ExecutedEvent, 
         new CanExecuteRoutedEventHandler((s, e) => Debug.WriteLine("Executed:" + s)), true);
    EventManager.RegisterClassHandler(typeof(FrameworkElement), CommandManager.ExecutedEvent, 
         new CanExecuteRoutedEventHandler((s, e) => Debug.WriteLine("KeyDown:" + s)), true);
    

    在您的情况下,KeyDown 可能在到达命令绑定之前被处理,或者 CanExecute 事件可能由于其他原因无法到达它。

    希望这将帮助您调试问题

    【讨论】:

      【解决方案2】:

      这可能是因为您使用的键是“向下”键。我怀疑如果您使用不同的密钥,它会起作用。

      某些控件会使用箭头键和向上/向下翻页键。例如,TextBox 就是这样做的。如果您的 Canvas 在滚动查看器中,则滚动查看器可能正在吃掉它。

      有两种解决方法:

      1. 向正在吃键手势的控件添加绑定。
      2. 处理 Canvas 的 KeyPreview(或正在吃键击的任何父控件)并从那里执行命令。

      this question 的答案展示了如何在不为每个命令的 KeyPreview 处理程序中编写特定代码的情况下执行 #2。

      【讨论】:

        【解决方案3】:

        原来是焦点问题,我只是在鼠标进入时将焦点设置在画布上,现在它已经修复了。谢谢大家的回答。

        【讨论】:

          猜你喜欢
          • 2011-05-27
          • 1970-01-01
          • 2015-05-11
          • 1970-01-01
          • 2023-03-24
          • 2018-12-13
          • 2013-12-02
          • 2019-04-05
          • 2019-11-13
          相关资源
          最近更新 更多