0

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

4

3 回答 3

2

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

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其他原因,事件可能无法到达它。

希望这将帮助您调试问题

于 2011-02-24T23:25:20.983 回答
2

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

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

有两种解决方法:

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

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

于 2011-02-25T07:57:17.177 回答
1

事实证明这是一个焦点问题,我只是在鼠标进入时将焦点设置在画布上,现在它已经修复了。谢谢大家的回答。

于 2011-02-28T16:26:56.503 回答