SplitButton.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using System;
  2. using System.Windows.Input;
  3. using Avalonia.Controls.Metadata;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Input;
  6. using Avalonia.Interactivity;
  7. using Avalonia.LogicalTree;
  8. using Avalonia.Reactive;
  9. namespace Avalonia.Controls
  10. {
  11. /// <summary>
  12. /// A button with primary and secondary parts that can each be pressed separately.
  13. /// The primary part behaves like a <see cref="Button"/> and the secondary part opens a flyout.
  14. /// </summary>
  15. [TemplatePart("PART_PrimaryButton", typeof(Button))]
  16. [TemplatePart("PART_SecondaryButton", typeof(Button))]
  17. [PseudoClasses(pcFlyoutOpen, pcPressed)]
  18. public class SplitButton : ContentControl, ICommandSource, IClickableControl
  19. {
  20. internal const string pcChecked = ":checked";
  21. internal const string pcPressed = ":pressed";
  22. internal const string pcFlyoutOpen = ":flyout-open";
  23. /// <summary>
  24. /// Raised when the user presses the primary part of the <see cref="SplitButton"/>.
  25. /// </summary>
  26. public event EventHandler<RoutedEventArgs>? Click
  27. {
  28. add => AddHandler(ClickEvent, value);
  29. remove => RemoveHandler(ClickEvent, value);
  30. }
  31. /// <summary>
  32. /// Defines the <see cref="Click"/> event.
  33. /// </summary>
  34. public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
  35. RoutedEvent.Register<SplitButton, RoutedEventArgs>(
  36. nameof(Click),
  37. RoutingStrategies.Bubble);
  38. /// <summary>
  39. /// Defines the <see cref="Command"/> property.
  40. /// </summary>
  41. public static readonly StyledProperty<ICommand?> CommandProperty =
  42. Button.CommandProperty.AddOwner<SplitButton>();
  43. /// <summary>
  44. /// Defines the <see cref="CommandParameter"/> property.
  45. /// </summary>
  46. public static readonly StyledProperty<object?> CommandParameterProperty =
  47. Button.CommandParameterProperty.AddOwner<SplitButton>();
  48. /// <summary>
  49. /// Defines the <see cref="Flyout"/> property
  50. /// </summary>
  51. public static readonly StyledProperty<FlyoutBase?> FlyoutProperty =
  52. Button.FlyoutProperty.AddOwner<SplitButton>();
  53. /// <summary>
  54. /// Defines the <see cref="HotKey"/> property.
  55. /// </summary>
  56. public static readonly StyledProperty<KeyGesture?> HotKeyProperty =
  57. Button.HotKeyProperty.AddOwner<SplitButton>();
  58. private Button? _primaryButton = null;
  59. private Button? _secondaryButton = null;
  60. private KeyGesture? _hotkey = default;
  61. private bool _commandCanExecute = true;
  62. private bool _isAttachedToLogicalTree = false;
  63. private bool _isFlyoutOpen = false;
  64. private bool _isKeyboardPressed = false;
  65. private IDisposable? _flyoutPropertyChangedDisposable;
  66. /// <summary>
  67. /// Initializes a new instance of the <see cref="SplitButton"/> class.
  68. /// </summary>
  69. public SplitButton()
  70. {
  71. }
  72. /// <summary>
  73. /// Gets or sets the <see cref="ICommand"/> invoked when the primary part is pressed.
  74. /// </summary>
  75. public ICommand? Command
  76. {
  77. get => GetValue(CommandProperty);
  78. set => SetValue(CommandProperty, value);
  79. }
  80. /// <summary>
  81. /// Gets or sets a parameter to be passed to the <see cref="Command"/>.
  82. /// </summary>
  83. public object? CommandParameter
  84. {
  85. get => GetValue(CommandParameterProperty);
  86. set => SetValue(CommandParameterProperty, value);
  87. }
  88. /// <summary>
  89. /// Gets or sets the <see cref="FlyoutBase"/> that is shown when the secondary part is pressed.
  90. /// </summary>
  91. public FlyoutBase? Flyout
  92. {
  93. get => GetValue(FlyoutProperty);
  94. set => SetValue(FlyoutProperty, value);
  95. }
  96. /// <summary>
  97. /// Gets or sets an <see cref="KeyGesture"/> associated with this control
  98. /// </summary>
  99. public KeyGesture? HotKey
  100. {
  101. get => GetValue(HotKeyProperty);
  102. set => SetValue(HotKeyProperty, value);
  103. }
  104. /// <summary>
  105. /// Gets a value indicating whether the button is currently checked.
  106. /// </summary>
  107. /// <remarks>
  108. /// This property exists only for the derived <see cref="ToggleSplitButton"/> and is
  109. /// unused (set to false) within <see cref="SplitButton"/>. Doing this allows the
  110. /// two controls to share a default style.
  111. /// </remarks>
  112. internal virtual bool InternalIsChecked => false;
  113. /// <inheritdoc/>
  114. protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute;
  115. /// <inheritdoc/>
  116. void ICommandSource.CanExecuteChanged(object sender, EventArgs e) => this.CanExecuteChanged(sender, e);
  117. /// <inheritdoc cref="ICommandSource.CanExecuteChanged"/>
  118. private void CanExecuteChanged(object? sender, EventArgs e)
  119. {
  120. (var command, var parameter) = (Command, CommandParameter);
  121. CanExecuteChanged(command, parameter);
  122. }
  123. private void CanExecuteChanged(ICommand? command, object? parameter)
  124. {
  125. if (!((ILogical)this).IsAttachedToLogicalTree)
  126. {
  127. return;
  128. }
  129. var canExecute = command is null || command.CanExecute(parameter);
  130. if (canExecute != _commandCanExecute)
  131. {
  132. _commandCanExecute = canExecute;
  133. UpdateIsEffectivelyEnabled();
  134. }
  135. }
  136. /// <summary>
  137. /// Updates the visual state of the control by applying latest PseudoClasses.
  138. /// </summary>
  139. protected void UpdatePseudoClasses()
  140. {
  141. PseudoClasses.Set(pcFlyoutOpen, _isFlyoutOpen);
  142. PseudoClasses.Set(pcPressed, _isKeyboardPressed);
  143. PseudoClasses.Set(pcChecked, InternalIsChecked);
  144. }
  145. /// <summary>
  146. /// Opens the secondary button's flyout.
  147. /// </summary>
  148. protected void OpenFlyout()
  149. {
  150. Flyout?.ShowAt(this);
  151. }
  152. /// <summary>
  153. /// Closes the secondary button's flyout.
  154. /// </summary>
  155. protected void CloseFlyout()
  156. {
  157. Flyout?.Hide();
  158. }
  159. /// <summary>
  160. /// Registers all flyout events.
  161. /// </summary>
  162. /// <param name="flyout">The flyout to connect events to.</param>
  163. private void RegisterFlyoutEvents(FlyoutBase? flyout)
  164. {
  165. if (flyout != null)
  166. {
  167. flyout.Opened += Flyout_Opened;
  168. flyout.Closed += Flyout_Closed;
  169. _flyoutPropertyChangedDisposable = flyout.GetPropertyChangedObservable(Popup.PlacementProperty).Subscribe(Flyout_PlacementPropertyChanged);
  170. }
  171. }
  172. /// <summary>
  173. /// Explicitly unregisters all flyout events.
  174. /// </summary>
  175. /// <param name="flyout">The flyout to disconnect events from.</param>
  176. private void UnregisterFlyoutEvents(FlyoutBase? flyout)
  177. {
  178. if (flyout != null)
  179. {
  180. flyout.Opened -= Flyout_Opened;
  181. flyout.Closed -= Flyout_Closed;
  182. _flyoutPropertyChangedDisposable?.Dispose();
  183. _flyoutPropertyChangedDisposable = null;
  184. }
  185. }
  186. /// <summary>
  187. /// Explicitly unregisters all events related to the two buttons in OnApplyTemplate().
  188. /// </summary>
  189. private void UnregisterEvents()
  190. {
  191. if (_primaryButton != null)
  192. {
  193. _primaryButton.Click -= PrimaryButton_Click;
  194. }
  195. if (_secondaryButton != null)
  196. {
  197. _secondaryButton.Click -= SecondaryButton_Click;
  198. _secondaryButton.RemoveHandler(PointerPressedEvent, SecondaryButton_PreviewPointerPressed);
  199. }
  200. }
  201. /// <inheritdoc/>
  202. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  203. {
  204. base.OnApplyTemplate(e);
  205. UnregisterEvents();
  206. UnregisterFlyoutEvents(Flyout);
  207. _primaryButton = e.NameScope.Find<Button>("PART_PrimaryButton");
  208. _secondaryButton = e.NameScope.Find<Button>("PART_SecondaryButton");
  209. if (_primaryButton != null)
  210. {
  211. _primaryButton.Click += PrimaryButton_Click;
  212. }
  213. if (_secondaryButton != null)
  214. {
  215. _secondaryButton.Click += SecondaryButton_Click;
  216. _secondaryButton.AddHandler(PointerPressedEvent, SecondaryButton_PreviewPointerPressed, RoutingStrategies.Tunnel);
  217. }
  218. RegisterFlyoutEvents(Flyout);
  219. UpdatePseudoClasses();
  220. }
  221. /// <inheritdoc/>
  222. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  223. {
  224. base.OnAttachedToLogicalTree(e);
  225. // Control attached again, set Hotkey to create a hotkey manager for this control
  226. SetCurrentValue(HotKeyProperty, _hotkey);
  227. if (Command != null)
  228. {
  229. Command.CanExecuteChanged += CanExecuteChanged;
  230. CanExecuteChanged(this, EventArgs.Empty);
  231. }
  232. _isAttachedToLogicalTree = true;
  233. }
  234. /// <inheritdoc/>
  235. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  236. {
  237. base.OnDetachedFromLogicalTree(e);
  238. // This will cause the hotkey manager to dispose the observer and the reference to this control
  239. _hotkey = HotKey;
  240. SetCurrentValue(HotKeyProperty, null);
  241. if (Command != null)
  242. {
  243. Command.CanExecuteChanged -= CanExecuteChanged;
  244. }
  245. _isAttachedToLogicalTree = false;
  246. }
  247. /// <inheritdoc/>
  248. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs e)
  249. {
  250. if (e.Property == CommandProperty)
  251. {
  252. // Must unregister events here while a reference to the old command still exists
  253. var (oldValue, newValue) = e.GetOldAndNewValue<ICommand?>();
  254. if (_isAttachedToLogicalTree)
  255. {
  256. if (oldValue is ICommand oldCommand)
  257. {
  258. oldCommand.CanExecuteChanged -= CanExecuteChanged;
  259. }
  260. if (newValue is ICommand newCommand)
  261. {
  262. newCommand.CanExecuteChanged += CanExecuteChanged;
  263. }
  264. }
  265. CanExecuteChanged(newValue, CommandParameter);
  266. }
  267. else if (e.Property == CommandParameterProperty && IsLoaded)
  268. {
  269. CanExecuteChanged(Command, e.NewValue);
  270. }
  271. else if (e.Property == FlyoutProperty)
  272. {
  273. var (oldFlyout, newFlyout) = e.GetOldAndNewValue<FlyoutBase?>();
  274. // If flyout is changed while one is already open, make sure we
  275. // close the old one first
  276. // This is the same behavior as Button
  277. if (oldFlyout != null &&
  278. oldFlyout.IsOpen)
  279. {
  280. oldFlyout.Hide();
  281. }
  282. // Must unregister events here while a reference to the old flyout still exists
  283. UnregisterFlyoutEvents(oldFlyout);
  284. RegisterFlyoutEvents(newFlyout);
  285. UpdatePseudoClasses();
  286. }
  287. base.OnPropertyChanged(e);
  288. }
  289. /// <inheritdoc/>
  290. protected override void OnKeyDown(KeyEventArgs e)
  291. {
  292. var key = e.Key;
  293. if ((IsFocused && key == Key.Space) || key == Key.Enter)
  294. {
  295. _isKeyboardPressed = true;
  296. UpdatePseudoClasses();
  297. }
  298. base.OnKeyDown(e);
  299. }
  300. /// <inheritdoc/>
  301. protected override void OnKeyUp(KeyEventArgs e)
  302. {
  303. var key = e.Key;
  304. if ((IsFocused && key == Key.Space) || key == Key.Enter)
  305. {
  306. _isKeyboardPressed = false;
  307. UpdatePseudoClasses();
  308. // Consider this a click on the primary button
  309. if (IsEffectivelyEnabled)
  310. {
  311. OnClickPrimary(null);
  312. e.Handled = true;
  313. }
  314. }
  315. else if (key == Key.Down && e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) && IsEffectivelyEnabled
  316. && !XYFocusHelpers.IsAllowedXYNavigationMode(this, e.KeyDeviceType))
  317. {
  318. OpenFlyout();
  319. e.Handled = true;
  320. }
  321. else if (key == Key.F4 && IsEffectivelyEnabled)
  322. {
  323. OpenFlyout();
  324. e.Handled = true;
  325. }
  326. else if (e.Key == Key.Escape && _isFlyoutOpen)
  327. {
  328. // If Flyout doesn't have focusable content, close the flyout here
  329. // This is the same behavior as Button
  330. CloseFlyout();
  331. e.Handled = true;
  332. }
  333. base.OnKeyUp(e);
  334. }
  335. /// <summary>
  336. /// Invokes the <see cref="Click"/> event when the primary button part is clicked.
  337. /// </summary>
  338. /// <param name="e">The event args from the internal Click event.</param>
  339. protected virtual void OnClickPrimary(RoutedEventArgs? e)
  340. {
  341. (var command, var parameter) = (Command, CommandParameter);
  342. // Note: It is not currently required to check enabled status; however, this is a failsafe
  343. if (IsEffectivelyEnabled)
  344. {
  345. var eventArgs = new RoutedEventArgs(ClickEvent);
  346. RaiseEvent(eventArgs);
  347. if (!eventArgs.Handled && command?.CanExecute(parameter) == true)
  348. {
  349. command.Execute(parameter);
  350. eventArgs.Handled = true;
  351. }
  352. }
  353. }
  354. /// <summary>
  355. /// Invoked when the secondary button part is clicked.
  356. /// </summary>
  357. /// <param name="e">The event args from the internal Click event.</param>
  358. protected virtual void OnClickSecondary(RoutedEventArgs? e)
  359. {
  360. // Note: It is not currently required to check enabled status; however, this is a failsafe
  361. if (IsEffectivelyEnabled)
  362. {
  363. if (_isFlyoutOpen)
  364. {
  365. CloseFlyout();
  366. }
  367. else
  368. {
  369. OpenFlyout();
  370. }
  371. }
  372. }
  373. /// <summary>
  374. /// Invoked when the split button's flyout is opened.
  375. /// </summary>
  376. protected virtual void OnFlyoutOpened()
  377. {
  378. // Available for derived types
  379. }
  380. /// <summary>
  381. /// Invoked when the split button's flyout is closed.
  382. /// </summary>
  383. protected virtual void OnFlyoutClosed()
  384. {
  385. // Available for derived types
  386. }
  387. /// <summary>
  388. /// Event handler for when the internal primary button part is clicked.
  389. /// </summary>
  390. private void PrimaryButton_Click(object? sender, RoutedEventArgs e)
  391. {
  392. // Handle internal button click, so it won't bubble outside together with SplitButton.ClickEvent.
  393. e.Handled = true;
  394. OnClickPrimary(e);
  395. }
  396. /// <summary>
  397. /// Event handler for when the internal secondary button part is clicked.
  398. /// </summary>
  399. private void SecondaryButton_Click(object? sender, RoutedEventArgs e)
  400. {
  401. // Handle internal button click, so it won't bubble outside.
  402. e.Handled = true;
  403. OnClickSecondary(e);
  404. }
  405. /// <summary>
  406. /// Event handler for when the internal secondary button part is pressed.
  407. /// </summary>
  408. private void SecondaryButton_PreviewPointerPressed(object? sender, PointerPressedEventArgs e)
  409. {
  410. if (_isFlyoutOpen && _secondaryButton?.IsEffectivelyEnabled == true)
  411. {
  412. if (e.GetCurrentPoint(_secondaryButton).Properties.IsLeftButtonPressed)
  413. {
  414. // When a flyout is open with OverlayDismissEventPassThrough enabled and the secondary button
  415. // is pressed, close the flyout
  416. e.Handled = true;
  417. OnClickSecondary(e);
  418. }
  419. }
  420. }
  421. /// <summary>
  422. /// Called when the <see cref="PopupFlyoutBase.Placement"/> property changes.
  423. /// </summary>
  424. private void Flyout_PlacementPropertyChanged(AvaloniaPropertyChangedEventArgs e)
  425. {
  426. UpdatePseudoClasses();
  427. }
  428. /// <summary>
  429. /// Event handler for when the split button's flyout is opened.
  430. /// </summary>
  431. private void Flyout_Opened(object? sender, EventArgs e)
  432. {
  433. var flyout = sender as FlyoutBase;
  434. // It is possible to share flyouts among multiple controls including SplitButton.
  435. // This can cause a problem here since all controls that share a flyout receive
  436. // the same Opened/Closed events at the same time.
  437. // For SplitButton that means they all would be updating their pseudoclasses accordingly.
  438. // In other words, all SplitButtons with a shared Flyout would have the backgrounds changed together.
  439. // To fix this, only continue here if the Flyout target matches this SplitButton instance.
  440. if (object.ReferenceEquals(flyout?.Target, this))
  441. {
  442. _isFlyoutOpen = true;
  443. UpdatePseudoClasses();
  444. OnFlyoutOpened();
  445. }
  446. }
  447. /// <summary>
  448. /// Event handler for when the split button's flyout is closed.
  449. /// </summary>
  450. private void Flyout_Closed(object? sender, EventArgs e)
  451. {
  452. var flyout = sender as FlyoutBase;
  453. // See comments in Flyout_Opened
  454. if (object.ReferenceEquals(flyout?.Target, this))
  455. {
  456. _isFlyoutOpen = false;
  457. UpdatePseudoClasses();
  458. OnFlyoutClosed();
  459. }
  460. }
  461. void IClickableControl.RaiseClick() =>
  462. (_primaryButton as IClickableControl)?.RaiseClick();
  463. }
  464. }