2011-02-24 36 views
0

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

工作的RoutedCommand:

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

回答

1

事实证明,这是一个焦点问题,我只是将鼠标放在画布上的焦点,现在它是固定的。谢谢大家回答。

2

可以sometiems使用非常包容类的事件处理程序跟踪事件的路线:

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事件可能不会达到它出于其他原因。

希望这将有助于你调试问题

1

这可能是由于您所使用的关键是“向下”键。我怀疑如果你使用了不同的密钥,它会起作用。

一些控件使用箭头键和pageup/pagedown键。例如,TextBox执行此操作。如果您的画布位于滚动查看器中,则滚动查看器可能正在吃它。

这有两种解决方法:

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

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