Button.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Linq;
  5. using System.Windows.Input;
  6. using Avalonia.Data;
  7. using Avalonia.Input;
  8. using Avalonia.Interactivity;
  9. using Avalonia.LogicalTree;
  10. using Avalonia.VisualTree;
  11. namespace Avalonia.Controls
  12. {
  13. /// <summary>
  14. /// Defines how a <see cref="Button"/> reacts to clicks.
  15. /// </summary>
  16. public enum ClickMode
  17. {
  18. /// <summary>
  19. /// The <see cref="Button.Click"/> event is raised when the pointer is released.
  20. /// </summary>
  21. Release,
  22. /// <summary>
  23. /// The <see cref="Button.Click"/> event is raised when the pointer is pressed.
  24. /// </summary>
  25. Press,
  26. }
  27. /// <summary>
  28. /// A button control.
  29. /// </summary>
  30. public class Button : ContentControl
  31. {
  32. /// <summary>
  33. /// Defines the <see cref="ClickMode"/> property.
  34. /// </summary>
  35. public static readonly StyledProperty<ClickMode> ClickModeProperty =
  36. AvaloniaProperty.Register<Button, ClickMode>(nameof(ClickMode));
  37. /// <summary>
  38. /// Defines the <see cref="Command"/> property.
  39. /// </summary>
  40. public static readonly DirectProperty<Button, ICommand> CommandProperty =
  41. AvaloniaProperty.RegisterDirect<Button, ICommand>(nameof(Command),
  42. button => button.Command, (button, command) => button.Command = command, enableDataValidation: true);
  43. /// <summary>
  44. /// Defines the <see cref="HotKey"/> property.
  45. /// </summary>
  46. public static readonly StyledProperty<KeyGesture> HotKeyProperty =
  47. HotKeyManager.HotKeyProperty.AddOwner<Button>();
  48. /// <summary>
  49. /// Defines the <see cref="CommandParameter"/> property.
  50. /// </summary>
  51. public static readonly StyledProperty<object> CommandParameterProperty =
  52. AvaloniaProperty.Register<Button, object>(nameof(CommandParameter));
  53. /// <summary>
  54. /// Defines the <see cref="IsDefaultProperty"/> property.
  55. /// </summary>
  56. public static readonly StyledProperty<bool> IsDefaultProperty =
  57. AvaloniaProperty.Register<Button, bool>(nameof(IsDefault));
  58. /// <summary>
  59. /// Defines the <see cref="IsCancelProperty"/> property.
  60. /// </summary>
  61. public static readonly StyledProperty<bool> IsCancelProperty =
  62. AvaloniaProperty.Register<Button, bool>(nameof(IsCancel));
  63. /// <summary>
  64. /// Defines the <see cref="Click"/> event.
  65. /// </summary>
  66. public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
  67. RoutedEvent.Register<Button, RoutedEventArgs>(nameof(Click), RoutingStrategies.Bubble);
  68. public static readonly StyledProperty<bool> IsPressedProperty =
  69. AvaloniaProperty.Register<Button, bool>(nameof(IsPressed));
  70. private ICommand _command;
  71. private bool _commandCanExecute = true;
  72. /// <summary>
  73. /// Initializes static members of the <see cref="Button"/> class.
  74. /// </summary>
  75. static Button()
  76. {
  77. FocusableProperty.OverrideDefaultValue(typeof(Button), true);
  78. CommandProperty.Changed.Subscribe(CommandChanged);
  79. IsDefaultProperty.Changed.Subscribe(IsDefaultChanged);
  80. IsCancelProperty.Changed.Subscribe(IsCancelChanged);
  81. }
  82. public Button()
  83. {
  84. UpdatePseudoClasses(IsPressed);
  85. }
  86. /// <summary>
  87. /// Raised when the user clicks the button.
  88. /// </summary>
  89. public event EventHandler<RoutedEventArgs> Click
  90. {
  91. add { AddHandler(ClickEvent, value); }
  92. remove { RemoveHandler(ClickEvent, value); }
  93. }
  94. /// <summary>
  95. /// Gets or sets a value indicating how the <see cref="Button"/> should react to clicks.
  96. /// </summary>
  97. public ClickMode ClickMode
  98. {
  99. get { return GetValue(ClickModeProperty); }
  100. set { SetValue(ClickModeProperty, value); }
  101. }
  102. /// <summary>
  103. /// Gets or sets an <see cref="ICommand"/> to be invoked when the button is clicked.
  104. /// </summary>
  105. public ICommand Command
  106. {
  107. get { return _command; }
  108. set { SetAndRaise(CommandProperty, ref _command, value); }
  109. }
  110. /// <summary>
  111. /// Gets or sets an <see cref="KeyGesture"/> associated with this control
  112. /// </summary>
  113. public KeyGesture HotKey
  114. {
  115. get { return GetValue(HotKeyProperty); }
  116. set { SetValue(HotKeyProperty, value); }
  117. }
  118. /// <summary>
  119. /// Gets or sets a parameter to be passed to the <see cref="Command"/>.
  120. /// </summary>
  121. public object CommandParameter
  122. {
  123. get { return GetValue(CommandParameterProperty); }
  124. set { SetValue(CommandParameterProperty, value); }
  125. }
  126. /// <summary>
  127. /// Gets or sets a value indicating whether the button is the default button for the
  128. /// window.
  129. /// </summary>
  130. public bool IsDefault
  131. {
  132. get { return GetValue(IsDefaultProperty); }
  133. set { SetValue(IsDefaultProperty, value); }
  134. }
  135. /// <summary>
  136. /// Gets or sets a value indicating whether the button is the Cancel button for the
  137. /// window.
  138. /// </summary>
  139. public bool IsCancel
  140. {
  141. get { return GetValue(IsCancelProperty); }
  142. set { SetValue(IsCancelProperty, value); }
  143. }
  144. public bool IsPressed
  145. {
  146. get { return GetValue(IsPressedProperty); }
  147. private set { SetValue(IsPressedProperty, value); }
  148. }
  149. protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute;
  150. /// <inheritdoc/>
  151. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  152. {
  153. base.OnAttachedToVisualTree(e);
  154. if (IsDefault)
  155. {
  156. if (e.Root is IInputElement inputElement)
  157. {
  158. ListenForDefault(inputElement);
  159. }
  160. }
  161. if (IsCancel)
  162. {
  163. if (e.Root is IInputElement inputElement)
  164. {
  165. ListenForCancel(inputElement);
  166. }
  167. }
  168. }
  169. /// <inheritdoc/>
  170. protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
  171. {
  172. base.OnDetachedFromVisualTree(e);
  173. if (IsDefault)
  174. {
  175. if (e.Root is IInputElement inputElement)
  176. {
  177. StopListeningForDefault(inputElement);
  178. }
  179. }
  180. }
  181. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  182. {
  183. base.OnAttachedToLogicalTree(e);
  184. if (Command != null)
  185. {
  186. Command.CanExecuteChanged += CanExecuteChanged;
  187. }
  188. }
  189. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  190. {
  191. base.OnDetachedFromLogicalTree(e);
  192. if (Command != null)
  193. {
  194. Command.CanExecuteChanged -= CanExecuteChanged;
  195. }
  196. }
  197. /// <inheritdoc/>
  198. protected override void OnKeyDown(KeyEventArgs e)
  199. {
  200. if (e.Key == Key.Enter)
  201. {
  202. OnClick();
  203. e.Handled = true;
  204. }
  205. else if (e.Key == Key.Space)
  206. {
  207. if (ClickMode == ClickMode.Press)
  208. {
  209. OnClick();
  210. }
  211. IsPressed = true;
  212. e.Handled = true;
  213. }
  214. base.OnKeyDown(e);
  215. }
  216. /// <inheritdoc/>
  217. protected override void OnKeyUp(KeyEventArgs e)
  218. {
  219. if (e.Key == Key.Space)
  220. {
  221. if (ClickMode == ClickMode.Release)
  222. {
  223. OnClick();
  224. }
  225. IsPressed = false;
  226. e.Handled = true;
  227. }
  228. }
  229. /// <summary>
  230. /// Invokes the <see cref="Click"/> event.
  231. /// </summary>
  232. protected virtual void OnClick()
  233. {
  234. var e = new RoutedEventArgs(ClickEvent);
  235. RaiseEvent(e);
  236. if (!e.Handled && Command?.CanExecute(CommandParameter) == true)
  237. {
  238. Command.Execute(CommandParameter);
  239. e.Handled = true;
  240. }
  241. }
  242. /// <inheritdoc/>
  243. protected override void OnPointerPressed(PointerPressedEventArgs e)
  244. {
  245. base.OnPointerPressed(e);
  246. if (e.MouseButton == MouseButton.Left)
  247. {
  248. IsPressed = true;
  249. e.Handled = true;
  250. if (ClickMode == ClickMode.Press)
  251. {
  252. OnClick();
  253. }
  254. }
  255. }
  256. /// <inheritdoc/>
  257. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  258. {
  259. base.OnPointerReleased(e);
  260. if (IsPressed && e.InitialPressMouseButton == MouseButton.Left)
  261. {
  262. IsPressed = false;
  263. e.Handled = true;
  264. if (ClickMode == ClickMode.Release &&
  265. this.GetVisualsAt(e.GetPosition(this)).Any(c => this == c || this.IsVisualAncestorOf(c)))
  266. {
  267. OnClick();
  268. }
  269. }
  270. }
  271. protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
  272. {
  273. IsPressed = false;
  274. }
  275. protected override void OnPropertyChanged<T>(
  276. AvaloniaProperty<T> property,
  277. Optional<T> oldValue,
  278. BindingValue<T> newValue,
  279. BindingPriority priority)
  280. {
  281. base.OnPropertyChanged(property, oldValue, newValue, priority);
  282. if (property == IsPressedProperty)
  283. {
  284. UpdatePseudoClasses(newValue.GetValueOrDefault<bool>());
  285. }
  286. }
  287. protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
  288. {
  289. base.UpdateDataValidation(property, value);
  290. if (property == CommandProperty)
  291. {
  292. if (value.Type == BindingValueType.BindingError)
  293. {
  294. if (_commandCanExecute)
  295. {
  296. _commandCanExecute = false;
  297. UpdateIsEffectivelyEnabled();
  298. }
  299. }
  300. }
  301. }
  302. /// <summary>
  303. /// Called when the <see cref="Command"/> property changes.
  304. /// </summary>
  305. /// <param name="e">The event args.</param>
  306. private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
  307. {
  308. if (e.Sender is Button button)
  309. {
  310. if (((ILogical)button).IsAttachedToLogicalTree)
  311. {
  312. if (e.OldValue is ICommand oldCommand)
  313. {
  314. oldCommand.CanExecuteChanged -= button.CanExecuteChanged;
  315. }
  316. if (e.NewValue is ICommand newCommand)
  317. {
  318. newCommand.CanExecuteChanged += button.CanExecuteChanged;
  319. }
  320. }
  321. button.CanExecuteChanged(button, EventArgs.Empty);
  322. }
  323. }
  324. /// <summary>
  325. /// Called when the <see cref="IsDefault"/> property changes.
  326. /// </summary>
  327. /// <param name="e">The event args.</param>
  328. private static void IsDefaultChanged(AvaloniaPropertyChangedEventArgs e)
  329. {
  330. var button = e.Sender as Button;
  331. var isDefault = (bool)e.NewValue;
  332. if (button?.VisualRoot is IInputElement inputRoot)
  333. {
  334. if (isDefault)
  335. {
  336. button.ListenForDefault(inputRoot);
  337. }
  338. else
  339. {
  340. button.StopListeningForDefault(inputRoot);
  341. }
  342. }
  343. }
  344. /// <summary>
  345. /// Called when the <see cref="IsCancel"/> property changes.
  346. /// </summary>
  347. /// <param name="e">The event args.</param>
  348. private static void IsCancelChanged(AvaloniaPropertyChangedEventArgs e)
  349. {
  350. var button = e.Sender as Button;
  351. var isCancel = (bool)e.NewValue;
  352. if (button?.VisualRoot is IInputElement inputRoot)
  353. {
  354. if (isCancel)
  355. {
  356. button.ListenForCancel(inputRoot);
  357. }
  358. else
  359. {
  360. button.StopListeningForCancel(inputRoot);
  361. }
  362. }
  363. }
  364. /// <summary>
  365. /// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
  366. /// </summary>
  367. /// <param name="sender">The event sender.</param>
  368. /// <param name="e">The event args.</param>
  369. private void CanExecuteChanged(object sender, EventArgs e)
  370. {
  371. var canExecute = Command == null || Command.CanExecute(CommandParameter);
  372. if (canExecute != _commandCanExecute)
  373. {
  374. _commandCanExecute = canExecute;
  375. UpdateIsEffectivelyEnabled();
  376. }
  377. }
  378. /// <summary>
  379. /// Starts listening for the Enter key when the button <see cref="IsDefault"/>.
  380. /// </summary>
  381. /// <param name="root">The input root.</param>
  382. private void ListenForDefault(IInputElement root)
  383. {
  384. root.AddHandler(KeyDownEvent, RootDefaultKeyDown);
  385. }
  386. /// <summary>
  387. /// Starts listening for the Escape key when the button <see cref="IsCancel"/>.
  388. /// </summary>
  389. /// <param name="root">The input root.</param>
  390. private void ListenForCancel(IInputElement root)
  391. {
  392. root.AddHandler(KeyDownEvent, RootCancelKeyDown);
  393. }
  394. /// <summary>
  395. /// Stops listening for the Enter key when the button is no longer <see cref="IsDefault"/>.
  396. /// </summary>
  397. /// <param name="root">The input root.</param>
  398. private void StopListeningForDefault(IInputElement root)
  399. {
  400. root.RemoveHandler(KeyDownEvent, RootDefaultKeyDown);
  401. }
  402. /// <summary>
  403. /// Stops listening for the Escape key when the button is no longer <see cref="IsCancel"/>.
  404. /// </summary>
  405. /// <param name="root">The input root.</param>
  406. private void StopListeningForCancel(IInputElement root)
  407. {
  408. root.RemoveHandler(KeyDownEvent, RootCancelKeyDown);
  409. }
  410. /// <summary>
  411. /// Called when a key is pressed on the input root and the button <see cref="IsDefault"/>.
  412. /// </summary>
  413. /// <param name="sender">The event sender.</param>
  414. /// <param name="e">The event args.</param>
  415. private void RootDefaultKeyDown(object sender, KeyEventArgs e)
  416. {
  417. if (e.Key == Key.Enter && IsVisible && IsEnabled)
  418. {
  419. OnClick();
  420. }
  421. }
  422. /// <summary>
  423. /// Called when a key is pressed on the input root and the button <see cref="IsCancel"/>.
  424. /// </summary>
  425. /// <param name="sender">The event sender.</param>
  426. /// <param name="e">The event args.</param>
  427. private void RootCancelKeyDown(object sender, KeyEventArgs e)
  428. {
  429. if (e.Key == Key.Escape && IsVisible && IsEnabled)
  430. {
  431. OnClick();
  432. }
  433. }
  434. private void UpdatePseudoClasses(bool isPressed)
  435. {
  436. PseudoClasses.Set(":pressed", isPressed);
  437. }
  438. }
  439. }