InvokeCommandAction.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Reflection;
  3. using System.Windows;
  4. using System.Windows.Input;
  5. namespace HandyControl.Interactivity;
  6. public sealed class InvokeCommandAction : TriggerAction<DependencyObject>
  7. {
  8. public static readonly DependencyProperty CommandProperty =
  9. DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(InvokeCommandAction), null);
  10. public static readonly DependencyProperty CommandParameterProperty =
  11. DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(InvokeCommandAction),
  12. null);
  13. private string _commandName;
  14. public string CommandName
  15. {
  16. get
  17. {
  18. ReadPreamble();
  19. return _commandName;
  20. }
  21. set
  22. {
  23. if (CommandName == value)
  24. return;
  25. WritePreamble();
  26. _commandName = value;
  27. WritePostscript();
  28. }
  29. }
  30. public ICommand Command
  31. {
  32. get => (ICommand) GetValue(CommandProperty);
  33. set => SetValue(CommandProperty, value);
  34. }
  35. public object CommandParameter
  36. {
  37. get => GetValue(CommandParameterProperty);
  38. set => SetValue(CommandParameterProperty, value);
  39. }
  40. protected override void Invoke(object parameter)
  41. {
  42. if (AssociatedObject == null)
  43. return;
  44. var command = ResolveCommand();
  45. if (command == null || !command.CanExecute(CommandParameter))
  46. return;
  47. command.Execute(CommandParameter);
  48. }
  49. private ICommand ResolveCommand()
  50. {
  51. var command = (ICommand) null;
  52. if (Command != null)
  53. command = Command;
  54. else if (AssociatedObject != null)
  55. foreach (var property in AssociatedObject.GetType()
  56. .GetProperties(BindingFlags.Instance | BindingFlags.Public))
  57. if (typeof(ICommand).IsAssignableFrom(property.PropertyType) &&
  58. string.Equals(property.Name, CommandName, StringComparison.Ordinal))
  59. command = (ICommand) property.GetValue(AssociatedObject, null);
  60. return command;
  61. }
  62. }