Behaviorでエンターキーによるフォーカス移動を実装したとき、DatePickerでは「FocusNavigationDirection.Next」または「FocusNavigationDirection.Previous」が動作しない場合があります。
動作しない一例
次のコードはEnterが押されたときに次のコントロール、Shift+Enterが押されたときは前のコントロールにフォーカス移動をしようとしています。ところが「FocusNavigationDirection.Next」は機能しますが「FocusNavigationDirection.Previous」は機能しないため、前のコントロールにフォーカスが移動しません。-
C#
private static void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (Keyboard.Modifiers == ModifierKeys.None) { UIElement element = e.OriginalSource as UIElement; element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); e.Handled = true; } else if (Keyboard.Modifiers == ModifierKeys.Shift) { UIElement element = e.OriginalSource as UIElement; element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous)); e.Handled = true; } } }
解決方法
UIElementを取得する際、第一引数の「object sender」または第二引数の「KeyEventArgs e.OriginalSource」を使用しますが、DatePickerでは「Keyboard.Modifiers」の値に応じて使い分けが必要になります。「Keyboard.Modifiers == ModifierKeys.None」 の場合は第二引数の「KeyEventArgs e.OriginalSource」、「Keyboard.Modifiers == ModifierKeys.Shift」の場合は第一引数の「object sender」を使用します。
-
C#
private static void OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (Keyboard.Modifiers == ModifierKeys.None) { UIElement element = e.OriginalSource as UIElement; element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); e.Handled = true; } else if (Keyboard.Modifiers == ModifierKeys.Shift) { UIElement element = sender as UIElement; element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous)); e.Handled = true; } } }
検証環境
- Microsoft Visual Studio Professional 2015 Version 14.0.25431.01 Update 3
- Microsoft .NET Framework Version 4.6.01055
- Microsoft Windows 7 Professional Service Pack 1 (Microsoft Windows NT 6.1 (7601))