ContextMenu.cs 15 KB

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