EnterKeyTraversal.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Windows;
  2. using System.Windows.Input;
  3. namespace GCHR.View
  4. {
  5. public class EnterKeyTraversal
  6. {
  7. public static bool GetIsEnabled(DependencyObject obj)
  8. {
  9. return (bool)obj.GetValue(IsEnabledProperty);
  10. }
  11. public static void SetIsEnabled(DependencyObject obj, bool value)
  12. {
  13. obj.SetValue(IsEnabledProperty, value);
  14. }
  15. static void ue_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
  16. {
  17. var ue = e.OriginalSource as FrameworkElement;
  18. if (e.Key == Key.Enter)
  19. {
  20. e.Handled = true;
  21. ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
  22. }
  23. }
  24. private static void ue_Unloaded(object sender, RoutedEventArgs e)
  25. {
  26. var ue = sender as FrameworkElement;
  27. if (ue == null) return;
  28. ue.Unloaded -= ue_Unloaded;
  29. ue.PreviewKeyDown -= ue_PreviewKeyDown;
  30. }
  31. public static readonly DependencyProperty IsEnabledProperty =
  32. DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
  33. typeof(EnterKeyTraversal), new UIPropertyMetadata(false, IsEnabledChanged));
  34. static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  35. {
  36. var ue = d as FrameworkElement;
  37. if (ue == null) return;
  38. if ((bool)e.NewValue)
  39. {
  40. ue.Unloaded += ue_Unloaded;
  41. ue.PreviewKeyDown += ue_PreviewKeyDown;
  42. }
  43. else
  44. {
  45. ue.PreviewKeyDown -= ue_PreviewKeyDown;
  46. }
  47. }
  48. }
  49. }