Button.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.Rendering;
  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="Click"/> event.
  60. /// </summary>
  61. public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
  62. RoutedEvent.Register<Button, RoutedEventArgs>("Click", RoutingStrategies.Bubble);
  63. private ICommand _command;
  64. /// <summary>
  65. /// Initializes static members of the <see cref="Button"/> class.
  66. /// </summary>
  67. static Button()
  68. {
  69. FocusableProperty.OverrideDefaultValue(typeof(Button), true);
  70. ClickEvent.AddClassHandler<Button>(x => x.OnClick);
  71. CommandProperty.Changed.Subscribe(CommandChanged);
  72. IsDefaultProperty.Changed.Subscribe(IsDefaultChanged);
  73. }
  74. /// <summary>
  75. /// Raised when the user clicks the button.
  76. /// </summary>
  77. public event EventHandler<RoutedEventArgs> Click
  78. {
  79. add { AddHandler(ClickEvent, value); }
  80. remove { RemoveHandler(ClickEvent, value); }
  81. }
  82. /// <summary>
  83. /// Gets or sets a value indicating how the <see cref="Button"/> should react to clicks.
  84. /// </summary>
  85. public ClickMode ClickMode
  86. {
  87. get { return GetValue(ClickModeProperty); }
  88. set { SetValue(ClickModeProperty, value); }
  89. }
  90. /// <summary>
  91. /// Gets or sets an <see cref="ICommand"/> to be invoked when the button is clicked.
  92. /// </summary>
  93. public ICommand Command
  94. {
  95. get { return _command; }
  96. set { SetAndRaise(CommandProperty, ref _command, value); }
  97. }
  98. /// <summary>
  99. /// Gets or sets an <see cref="KeyGesture"/> associated with this control
  100. /// </summary>
  101. public KeyGesture HotKey
  102. {
  103. get { return GetValue(HotKeyProperty); }
  104. set { SetValue(HotKeyProperty, value); }
  105. }
  106. /// <summary>
  107. /// Gets or sets a parameter to be passed to the <see cref="Command"/>.
  108. /// </summary>
  109. public object CommandParameter
  110. {
  111. get { return GetValue(CommandParameterProperty); }
  112. set { SetValue(CommandParameterProperty, value); }
  113. }
  114. /// <summary>
  115. /// Gets or sets a value indicating whether the button is the default button for the
  116. /// window.
  117. /// </summary>
  118. public bool IsDefault
  119. {
  120. get { return GetValue(IsDefaultProperty); }
  121. set { SetValue(IsDefaultProperty, value); }
  122. }
  123. /// <inheritdoc/>
  124. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  125. {
  126. base.OnAttachedToVisualTree(e);
  127. if (IsDefault)
  128. {
  129. var inputElement = e.Root as IInputElement;
  130. if (inputElement != null)
  131. {
  132. ListenForDefault(inputElement);
  133. }
  134. }
  135. }
  136. /// <inheritdoc/>
  137. protected override void OnKeyDown(KeyEventArgs e)
  138. {
  139. if (e.Key == Key.Enter)
  140. {
  141. RaiseClickEvent();
  142. e.Handled = true;
  143. }
  144. else if (e.Key == Key.Space)
  145. {
  146. if (ClickMode == ClickMode.Press)
  147. {
  148. RaiseClickEvent();
  149. }
  150. e.Handled = true;
  151. }
  152. base.OnKeyDown(e);
  153. }
  154. /// <inheritdoc/>
  155. protected override void OnKeyUp(KeyEventArgs e)
  156. {
  157. if (e.Key == Key.Space)
  158. {
  159. if (ClickMode == ClickMode.Release)
  160. {
  161. RaiseClickEvent();
  162. }
  163. e.Handled = true;
  164. }
  165. }
  166. /// <inheritdoc/>
  167. protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
  168. {
  169. base.OnDetachedFromVisualTree(e);
  170. if (IsDefault)
  171. {
  172. var inputElement = e.Root as IInputElement;
  173. if (inputElement != null)
  174. {
  175. StopListeningForDefault(inputElement);
  176. }
  177. }
  178. }
  179. /// <summary>
  180. /// Invokes the <see cref="Click"/> event.
  181. /// </summary>
  182. /// <param name="e">The event args.</param>
  183. protected virtual void OnClick(RoutedEventArgs e)
  184. {
  185. if (Command != null)
  186. {
  187. Command.Execute(CommandParameter);
  188. e.Handled = true;
  189. }
  190. }
  191. /// <inheritdoc/>
  192. protected override void OnPointerPressed(PointerPressedEventArgs e)
  193. {
  194. base.OnPointerPressed(e);
  195. if (e.MouseButton == MouseButton.Left)
  196. {
  197. PseudoClasses.Add(":pressed");
  198. e.Device.Capture(this);
  199. e.Handled = true;
  200. if (ClickMode == ClickMode.Press)
  201. {
  202. RaiseClickEvent();
  203. }
  204. }
  205. }
  206. /// <inheritdoc/>
  207. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  208. {
  209. base.OnPointerReleased(e);
  210. if (e.MouseButton == MouseButton.Left)
  211. {
  212. e.Device.Capture(null);
  213. PseudoClasses.Remove(":pressed");
  214. e.Handled = true;
  215. if (ClickMode == ClickMode.Release && new Rect(Bounds.Size).Contains(e.GetPosition(this)))
  216. {
  217. RaiseClickEvent();
  218. }
  219. }
  220. }
  221. protected override void UpdateDataValidation(AvaloniaProperty property, BindingNotification status)
  222. {
  223. base.UpdateDataValidation(property, status);
  224. if(property == CommandProperty)
  225. {
  226. if(status?.ErrorType == BindingErrorType.Error)
  227. {
  228. IsEnabled = false;
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// Called when the <see cref="Command"/> property changes.
  234. /// </summary>
  235. /// <param name="e">The event args.</param>
  236. private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
  237. {
  238. var button = e.Sender as Button;
  239. if (button != null)
  240. {
  241. var oldCommand = e.OldValue as ICommand;
  242. var newCommand = e.NewValue as ICommand;
  243. if (oldCommand != null)
  244. {
  245. oldCommand.CanExecuteChanged -= button.CanExecuteChanged;
  246. }
  247. if (newCommand != null)
  248. {
  249. newCommand.CanExecuteChanged += button.CanExecuteChanged;
  250. }
  251. button.CanExecuteChanged(button, EventArgs.Empty);
  252. }
  253. }
  254. /// <summary>
  255. /// Called when the <see cref="IsDefault"/> property changes.
  256. /// </summary>
  257. /// <param name="e">The event args.</param>
  258. private static void IsDefaultChanged(AvaloniaPropertyChangedEventArgs e)
  259. {
  260. var button = e.Sender as Button;
  261. var isDefault = (bool)e.NewValue;
  262. var inputRoot = button?.VisualRoot as IInputElement;
  263. if (inputRoot != null)
  264. {
  265. if (isDefault)
  266. {
  267. button.ListenForDefault(inputRoot);
  268. }
  269. else
  270. {
  271. button.StopListeningForDefault(inputRoot);
  272. }
  273. }
  274. }
  275. /// <summary>
  276. /// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
  277. /// </summary>
  278. /// <param name="sender">The event sender.</param>
  279. /// <param name="e">The event args.</param>
  280. private void CanExecuteChanged(object sender, EventArgs e)
  281. {
  282. // HACK: Just set the IsEnabled property for the moment. This needs to be changed to
  283. // use IsEnabledCore etc. but it will do for now.
  284. IsEnabled = Command == null || Command.CanExecute(CommandParameter);
  285. }
  286. /// <summary>
  287. /// Starts listening for the Enter key when the button <see cref="IsDefault"/>.
  288. /// </summary>
  289. /// <param name="root">The input root.</param>
  290. private void ListenForDefault(IInputElement root)
  291. {
  292. root.AddHandler(KeyDownEvent, RootKeyDown);
  293. }
  294. /// <summary>
  295. /// Stops listening for the Enter key when the button is no longer <see cref="IsDefault"/>.
  296. /// </summary>
  297. /// <param name="root">The input root.</param>
  298. private void StopListeningForDefault(IInputElement root)
  299. {
  300. root.RemoveHandler(KeyDownEvent, RootKeyDown);
  301. }
  302. /// <summary>
  303. /// Raises the <see cref="Click"/> event.
  304. /// </summary>
  305. private void RaiseClickEvent()
  306. {
  307. RoutedEventArgs click = new RoutedEventArgs
  308. {
  309. RoutedEvent = ClickEvent,
  310. };
  311. RaiseEvent(click);
  312. }
  313. /// <summary>
  314. /// Called when a key is pressed on the input root and the button <see cref="IsDefault"/>.
  315. /// </summary>
  316. /// <param name="sender">The event sender.</param>
  317. /// <param name="e">The event args.</param>
  318. private void RootKeyDown(object sender, KeyEventArgs e)
  319. {
  320. if (e.Key == Key.Enter && IsVisible && IsEnabled)
  321. {
  322. RaiseClickEvent();
  323. }
  324. }
  325. }
  326. }