ControlDoubleClickBehavior.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Input;
  9. namespace WpfStyleableWindow.StyleableWindow
  10. {
  11. public static class ControlDoubleClickBehavior
  12. {
  13. public static ICommand GetExecuteCommand(DependencyObject obj)
  14. {
  15. return (ICommand)obj.GetValue(ExecuteCommand);
  16. }
  17. public static void SetExecuteCommand(DependencyObject obj, ICommand command)
  18. {
  19. obj.SetValue(ExecuteCommand, command);
  20. }
  21. public static readonly DependencyProperty ExecuteCommand = DependencyProperty.RegisterAttached("ExecuteCommand",
  22. typeof(ICommand), typeof(ControlDoubleClickBehavior),
  23. new UIPropertyMetadata(null, OnExecuteCommandChanged));
  24. public static Window GetExecuteCommandParameter(DependencyObject obj)
  25. {
  26. return (Window) obj.GetValue(ExecuteCommandParameter);
  27. }
  28. public static void SetExecuteCommandParameter(DependencyObject obj, ICommand command)
  29. {
  30. obj.SetValue(ExecuteCommandParameter, command);
  31. }
  32. public static readonly DependencyProperty ExecuteCommandParameter = DependencyProperty.RegisterAttached("ExecuteCommandParameter",
  33. typeof(Window), typeof(ControlDoubleClickBehavior));
  34. private static void OnExecuteCommandChanged(object sender, DependencyPropertyChangedEventArgs e)
  35. {
  36. var control = sender as Control;
  37. if (control != null)
  38. {
  39. control.MouseDoubleClick += control_MouseDoubleClick;
  40. }
  41. }
  42. static void control_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  43. {
  44. var control = sender as Control;
  45. if(control != null)
  46. {
  47. var command = control.GetValue(ExecuteCommand) as ICommand;
  48. var commandParameter = control.GetValue(ExecuteCommandParameter);
  49. if (command.CanExecute(e))
  50. {
  51. command.Execute(commandParameter);
  52. }
  53. }
  54. }
  55. }
  56. }