ContextMenu.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using Avalonia.Automation.Peers;
  5. using System.Linq;
  6. using Avalonia.Controls.Diagnostics;
  7. using Avalonia.Controls.Generators;
  8. using Avalonia.Controls.Platform;
  9. using Avalonia.Controls.Primitives;
  10. using Avalonia.Controls.Primitives.PopupPositioning;
  11. using Avalonia.Controls.Templates;
  12. using Avalonia.Input;
  13. using Avalonia.Input.Platform;
  14. using Avalonia.Interactivity;
  15. using Avalonia.Layout;
  16. using Avalonia.Styling;
  17. using Avalonia.Automation;
  18. using Avalonia.Reactive;
  19. namespace Avalonia.Controls
  20. {
  21. /// <summary>
  22. /// A control context menu.
  23. /// </summary>
  24. public class ContextMenu : MenuBase, ISetterValue, IPopupHostProvider
  25. {
  26. /// <summary>
  27. /// Defines the <see cref="HorizontalOffset"/> property.
  28. /// </summary>
  29. public static readonly StyledProperty<double> HorizontalOffsetProperty =
  30. Popup.HorizontalOffsetProperty.AddOwner<ContextMenu>();
  31. /// <summary>
  32. /// Defines the <see cref="VerticalOffset"/> property.
  33. /// </summary>
  34. public static readonly StyledProperty<double> VerticalOffsetProperty =
  35. Popup.VerticalOffsetProperty.AddOwner<ContextMenu>();
  36. /// <summary>
  37. /// Defines the <see cref="PlacementAnchor"/> property.
  38. /// </summary>
  39. public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty =
  40. Popup.PlacementAnchorProperty.AddOwner<ContextMenu>();
  41. /// <summary>
  42. /// Defines the <see cref="PlacementConstraintAdjustment"/> property.
  43. /// </summary>
  44. public static readonly StyledProperty<PopupPositionerConstraintAdjustment> PlacementConstraintAdjustmentProperty =
  45. Popup.PlacementConstraintAdjustmentProperty.AddOwner<ContextMenu>();
  46. /// <summary>
  47. /// Defines the <see cref="PlacementGravity"/> property.
  48. /// </summary>
  49. public static readonly StyledProperty<PopupGravity> PlacementGravityProperty =
  50. Popup.PlacementGravityProperty.AddOwner<ContextMenu>();
  51. /// <summary>
  52. /// Defines the <see cref="PlacementMode"/> property.
  53. /// </summary>
  54. public static readonly StyledProperty<PlacementMode> PlacementModeProperty =
  55. Popup.PlacementProperty.AddOwner<ContextMenu>();
  56. /// <summary>
  57. /// Defines the <see cref="PlacementRect"/> property.
  58. /// </summary>
  59. public static readonly StyledProperty<Rect?> PlacementRectProperty =
  60. Popup.PlacementRectProperty.AddOwner<ContextMenu>();
  61. /// <summary>
  62. /// Defines the <see cref="WindowManagerAddShadowHint"/> property.
  63. /// </summary>
  64. public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty =
  65. Popup.WindowManagerAddShadowHintProperty.AddOwner<ContextMenu>();
  66. /// <summary>
  67. /// Defines the <see cref="PlacementTarget"/> property.
  68. /// </summary>
  69. public static readonly StyledProperty<Control?> PlacementTargetProperty =
  70. Popup.PlacementTargetProperty.AddOwner<ContextMenu>();
  71. private static readonly ITemplate<Panel> DefaultPanel =
  72. new FuncTemplate<Panel>(() => new StackPanel { Orientation = Orientation.Vertical });
  73. private Popup? _popup;
  74. private List<Control>? _attachedControls;
  75. private IInputElement? _previousFocus;
  76. private Action<IPopupHost?>? _popupHostChangedHandler;
  77. /// <summary>
  78. /// Initializes a new instance of the <see cref="ContextMenu"/> class.
  79. /// </summary>
  80. public ContextMenu()
  81. : this(new DefaultMenuInteractionHandler(true))
  82. {
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of the <see cref="ContextMenu"/> class.
  86. /// </summary>
  87. /// <param name="interactionHandler">The menu interaction handler.</param>
  88. public ContextMenu(IMenuInteractionHandler interactionHandler)
  89. : base(interactionHandler)
  90. {
  91. }
  92. /// <summary>
  93. /// Initializes static members of the <see cref="ContextMenu"/> class.
  94. /// </summary>
  95. static ContextMenu()
  96. {
  97. ItemsPanelProperty.OverrideDefaultValue<ContextMenu>(DefaultPanel);
  98. PlacementModeProperty.OverrideDefaultValue<ContextMenu>(PlacementMode.Pointer);
  99. ContextMenuProperty.Changed.Subscribe(ContextMenuChanged);
  100. AutomationProperties.AccessibilityViewProperty.OverrideDefaultValue<ContextMenu>(AccessibilityView.Control);
  101. AutomationProperties.ControlTypeOverrideProperty.OverrideDefaultValue<ContextMenu>(AutomationControlType.Menu);
  102. }
  103. /// <summary>
  104. /// Gets or sets the Horizontal offset of the context menu in relation to the <see cref="PlacementTarget"/>.
  105. /// </summary>
  106. public double HorizontalOffset
  107. {
  108. get { return GetValue(HorizontalOffsetProperty); }
  109. set { SetValue(HorizontalOffsetProperty, value); }
  110. }
  111. /// <summary>
  112. /// Gets or sets the Vertical offset of the context menu in relation to the <see cref="PlacementTarget"/>.
  113. /// </summary>
  114. public double VerticalOffset
  115. {
  116. get { return GetValue(VerticalOffsetProperty); }
  117. set { SetValue(VerticalOffsetProperty, value); }
  118. }
  119. /// <summary>
  120. /// Gets or sets the anchor point on the <see cref="PlacementRect"/> when <see cref="PlacementMode"/>
  121. /// is <see cref="PlacementMode.AnchorAndGravity"/>.
  122. /// </summary>
  123. public PopupAnchor PlacementAnchor
  124. {
  125. get { return GetValue(PlacementAnchorProperty); }
  126. set { SetValue(PlacementAnchorProperty, value); }
  127. }
  128. /// <summary>
  129. /// Gets or sets a value describing how the context menu position will be adjusted if the
  130. /// unadjusted position would result in the context menu being partly constrained.
  131. /// </summary>
  132. public PopupPositionerConstraintAdjustment PlacementConstraintAdjustment
  133. {
  134. get { return GetValue(PlacementConstraintAdjustmentProperty); }
  135. set { SetValue(PlacementConstraintAdjustmentProperty, value); }
  136. }
  137. /// <summary>
  138. /// Gets or sets a value which defines in what direction the context menu should open
  139. /// when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>.
  140. /// </summary>
  141. public PopupGravity PlacementGravity
  142. {
  143. get { return GetValue(PlacementGravityProperty); }
  144. set { SetValue(PlacementGravityProperty, value); }
  145. }
  146. /// <summary>
  147. /// Gets or sets the placement mode of the context menu in relation to the<see cref="PlacementTarget"/>.
  148. /// </summary>
  149. public PlacementMode PlacementMode
  150. {
  151. get { return GetValue(PlacementModeProperty); }
  152. set { SetValue(PlacementModeProperty, value); }
  153. }
  154. public bool WindowManagerAddShadowHint
  155. {
  156. get { return GetValue(WindowManagerAddShadowHintProperty); }
  157. set { SetValue(WindowManagerAddShadowHintProperty, value); }
  158. }
  159. /// <summary>
  160. /// Gets or sets the the anchor rectangle within the parent that the context menu will be placed
  161. /// relative to when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>.
  162. /// </summary>
  163. /// <remarks>
  164. /// The placement rect defines a rectangle relative to <see cref="PlacementTarget"/> around
  165. /// which the popup will be opened, with <see cref="PlacementAnchor"/> determining which edge
  166. /// of the placement target is used.
  167. ///
  168. /// If unset, the anchor rectangle will be the bounds of the <see cref="PlacementTarget"/>.
  169. /// </remarks>
  170. public Rect? PlacementRect
  171. {
  172. get { return GetValue(PlacementRectProperty); }
  173. set { SetValue(PlacementRectProperty, value); }
  174. }
  175. /// <summary>
  176. /// Gets or sets the control that is used to determine the popup's position.
  177. /// </summary>
  178. public Control? PlacementTarget
  179. {
  180. get { return GetValue(PlacementTargetProperty); }
  181. set { SetValue(PlacementTargetProperty, value); }
  182. }
  183. /// <summary>
  184. /// Occurs when the value of the
  185. /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" />
  186. /// property is changing from false to true.
  187. /// </summary>
  188. public event CancelEventHandler? ContextMenuOpening;
  189. /// <summary>
  190. /// Occurs when the value of the
  191. /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" />
  192. /// property is changing from true to false.
  193. /// </summary>
  194. public event CancelEventHandler? ContextMenuClosing;
  195. /// <summary>
  196. /// Called when the <see cref="Control.ContextMenu"/> property changes on a control.
  197. /// </summary>
  198. /// <param name="e">The event args.</param>
  199. private static void ContextMenuChanged(AvaloniaPropertyChangedEventArgs e)
  200. {
  201. var control = (Control)e.Sender;
  202. if (e.OldValue is ContextMenu oldMenu)
  203. {
  204. control.ContextRequested -= ControlContextRequested;
  205. control.DetachedFromVisualTree -= ControlDetachedFromVisualTree;
  206. oldMenu._attachedControls?.Remove(control);
  207. ((ISetLogicalParent?)oldMenu._popup)?.SetParent(null);
  208. }
  209. if (e.NewValue is ContextMenu newMenu)
  210. {
  211. newMenu._attachedControls ??= new List<Control>();
  212. newMenu._attachedControls.Add(control);
  213. control.ContextRequested += ControlContextRequested;
  214. control.DetachedFromVisualTree += ControlDetachedFromVisualTree;
  215. }
  216. }
  217. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  218. {
  219. base.OnPropertyChanged(change);
  220. if (change.Property == WindowManagerAddShadowHintProperty && _popup != null)
  221. {
  222. _popup.WindowManagerAddShadowHint = change.GetNewValue<bool>();
  223. }
  224. }
  225. /// <summary>
  226. /// Opens the menu.
  227. /// </summary>
  228. public override void Open() => Open(null);
  229. /// <summary>
  230. /// Opens a context menu on the specified control.
  231. /// </summary>
  232. /// <param name="control">The control.</param>
  233. public void Open(Control? control)
  234. {
  235. if (control is null && (_attachedControls is null || _attachedControls.Count == 0))
  236. {
  237. throw new ArgumentNullException(nameof(control));
  238. }
  239. if (control is object &&
  240. _attachedControls is object &&
  241. !_attachedControls.Contains(control))
  242. {
  243. throw new ArgumentException(
  244. "Cannot show ContentMenu on a different control to the one it is attached to.",
  245. nameof(control));
  246. }
  247. control ??= _attachedControls![0];
  248. Open(control, PlacementTarget ?? control, false);
  249. }
  250. /// <summary>
  251. /// Closes the menu.
  252. /// </summary>
  253. public override void Close()
  254. {
  255. if (!IsOpen)
  256. {
  257. return;
  258. }
  259. if (_popup != null && _popup.IsVisible)
  260. {
  261. _popup.IsOpen = false;
  262. }
  263. }
  264. void ISetterValue.Initialize(ISetter setter)
  265. {
  266. // ContextMenu can be assigned to the ContextMenu property in a setter. This overrides
  267. // the behavior defined in Control which requires controls to be wrapped in a <template>.
  268. if (!(setter is Setter s && s.Property == ContextMenuProperty))
  269. {
  270. throw new InvalidOperationException(
  271. "Cannot use a control as a Setter value. Wrap the control in a <Template>.");
  272. }
  273. }
  274. IPopupHost? IPopupHostProvider.PopupHost => _popup?.Host;
  275. event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged
  276. {
  277. add => _popupHostChangedHandler += value;
  278. remove => _popupHostChangedHandler -= value;
  279. }
  280. private void Open(Control control, Control placementTarget, bool requestedByPointer)
  281. {
  282. if (IsOpen)
  283. {
  284. return;
  285. }
  286. if (_popup == null)
  287. {
  288. _popup = new Popup
  289. {
  290. IsLightDismissEnabled = true,
  291. OverlayDismissEventPassThrough = true,
  292. };
  293. _popup.Opened += PopupOpened;
  294. _popup.Closed += PopupClosed;
  295. _popup.Closing += PopupClosing;
  296. _popup.KeyUp += PopupKeyUp;
  297. }
  298. if (_popup.Parent != control)
  299. {
  300. ((ISetLogicalParent)_popup).SetParent(null);
  301. ((ISetLogicalParent)_popup).SetParent(control);
  302. }
  303. _popup.Placement = !requestedByPointer && PlacementMode == PlacementMode.Pointer
  304. ? PlacementMode.Bottom
  305. : PlacementMode;
  306. //Position of the line below is really important.
  307. //All styles are being applied only when control has logical parent.
  308. //Line below will add ContextMenu as child to the Popup and this will trigger styles and they would be applied.
  309. //If you will move line below somewhere else it may cause that ContextMenu will behave differently from what you are expecting.
  310. _popup.Child = this;
  311. _popup.PlacementTarget = placementTarget;
  312. _popup.HorizontalOffset = HorizontalOffset;
  313. _popup.VerticalOffset = VerticalOffset;
  314. _popup.PlacementAnchor = PlacementAnchor;
  315. _popup.PlacementConstraintAdjustment = PlacementConstraintAdjustment;
  316. _popup.PlacementGravity = PlacementGravity;
  317. _popup.PlacementRect = PlacementRect;
  318. _popup.WindowManagerAddShadowHint = WindowManagerAddShadowHint;
  319. IsOpen = true;
  320. _popup.IsOpen = true;
  321. RaiseEvent(new RoutedEventArgs
  322. {
  323. RoutedEvent = MenuOpenedEvent,
  324. Source = this,
  325. });
  326. }
  327. private void PopupOpened(object? sender, EventArgs e)
  328. {
  329. _previousFocus = FocusManager.Instance?.Current;
  330. Focus();
  331. _popupHostChangedHandler?.Invoke(_popup!.Host);
  332. }
  333. private void PopupClosing(object? sender, CancelEventArgs e)
  334. {
  335. e.Cancel = CancelClosing();
  336. }
  337. private void PopupClosed(object? sender, EventArgs e)
  338. {
  339. foreach (var i in LogicalChildren)
  340. {
  341. if (i is MenuItem menuItem)
  342. {
  343. menuItem.IsSubMenuOpen = false;
  344. }
  345. }
  346. SelectedIndex = -1;
  347. IsOpen = false;
  348. if (_attachedControls is null || _attachedControls.Count == 0)
  349. {
  350. ((ISetLogicalParent)_popup!).SetParent(null);
  351. }
  352. // HACK: Reset the focus when the popup is closed. We need to fix this so it's automatic.
  353. FocusManager.Instance?.Focus(_previousFocus);
  354. RaiseEvent(new RoutedEventArgs
  355. {
  356. RoutedEvent = MenuClosedEvent,
  357. Source = this,
  358. });
  359. _popupHostChangedHandler?.Invoke(null);
  360. }
  361. private void PopupKeyUp(object? sender, KeyEventArgs e)
  362. {
  363. if (IsOpen)
  364. {
  365. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
  366. if (keymap?.OpenContextMenu.Any(k => k.Matches(e)) == true
  367. && !CancelClosing())
  368. {
  369. Close();
  370. e.Handled = true;
  371. }
  372. }
  373. }
  374. private static void ControlContextRequested(object? sender, ContextRequestedEventArgs e)
  375. {
  376. if (sender is Control control
  377. && control.ContextMenu is ContextMenu contextMenu
  378. && !e.Handled
  379. && !contextMenu.CancelOpening())
  380. {
  381. var requestedByPointer = e.TryGetPosition(null, out _);
  382. contextMenu.Open(control, e.Source as Control ?? control, requestedByPointer);
  383. e.Handled = true;
  384. }
  385. }
  386. private static void ControlDetachedFromVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
  387. {
  388. if (sender is Control control
  389. && control.ContextMenu is ContextMenu contextMenu)
  390. {
  391. if (contextMenu._popup?.Parent == control)
  392. {
  393. ((ISetLogicalParent)contextMenu._popup).SetParent(null);
  394. }
  395. contextMenu.Close();
  396. }
  397. }
  398. private bool CancelClosing()
  399. {
  400. var eventArgs = new CancelEventArgs();
  401. ContextMenuClosing?.Invoke(this, eventArgs);
  402. return eventArgs.Cancel;
  403. }
  404. private bool CancelOpening()
  405. {
  406. var eventArgs = new CancelEventArgs();
  407. ContextMenuOpening?.Invoke(this, eventArgs);
  408. return eventArgs.Cancel;
  409. }
  410. }
  411. }