diff --git a/src/Avalonia.Controls/Control.cs b/src/Avalonia.Controls/Control.cs index 4aab92c428..ebfe98a175 100644 --- a/src/Avalonia.Controls/Control.cs +++ b/src/Avalonia.Controls/Control.cs @@ -37,9 +37,16 @@ namespace Avalonia.Controls /// /// Defines the property. /// + [Obsolete("Prefer ContextFlyout")] public static readonly StyledProperty ContextMenuProperty = AvaloniaProperty.Register(nameof(ContextMenu)); + /// + /// Defines the property + /// + public static readonly StyledProperty ContextFlyoutProperty = + AvaloniaProperty.Register(nameof(ContextFlyout)); + /// /// Event raised when an element wishes to be scrolled into view. /// @@ -70,12 +77,22 @@ namespace Avalonia.Controls /// /// Gets or sets a context menu to the control. /// + [Obsolete("Prefer ContextFlyout")] public ContextMenu? ContextMenu { get => GetValue(ContextMenuProperty); set => SetValue(ContextMenuProperty, value); } + /// + /// Gets or sets a context flyout to the control + /// + public FlyoutBase? ContextFlyout + { + get => GetValue(ContextFlyoutProperty); + set => SetValue(ContextFlyoutProperty, value); + } + /// /// Gets or sets a user-defined object attached to the control. /// diff --git a/src/Avalonia.Controls/Flyouts/FlyoutBase.cs b/src/Avalonia.Controls/Flyouts/FlyoutBase.cs index 85e460a25f..f3f4febbb0 100644 --- a/src/Avalonia.Controls/Flyouts/FlyoutBase.cs +++ b/src/Avalonia.Controls/Flyouts/FlyoutBase.cs @@ -10,6 +10,11 @@ namespace Avalonia.Controls.Primitives { public abstract class FlyoutBase : AvaloniaObject { + static FlyoutBase() + { + Control.ContextFlyoutProperty.Changed.Subscribe(OnContextFlyoutPropertyChanged); + } + private static readonly DirectProperty IsOpenProperty = AvaloniaProperty.RegisterDirect(nameof(IsOpen), x => x.IsOpen); @@ -383,5 +388,36 @@ namespace Avalonia.Controls.Primitives break; } } + + private static void OnContextFlyoutPropertyChanged(AvaloniaPropertyChangedEventArgs args) + { + if (args.Sender is Control c) + { + if (args.OldValue.GetValueOrDefault() is FlyoutBase) + { + c.PointerReleased -= OnControlWithContextFlyoutPointerReleased; + } + if (args.NewValue.GetValueOrDefault() is FlyoutBase) + { + c.PointerReleased += OnControlWithContextFlyoutPointerReleased; + } + } + } + + private static void OnControlWithContextFlyoutPointerReleased(object sender, PointerReleasedEventArgs e) + { + if (sender is Control c) + { + if (e.InitialPressMouseButton == MouseButton.Right && + e.GetCurrentPoint(c).Properties.PointerUpdateKind == PointerUpdateKind.RightButtonReleased) + { + if (c.ContextFlyout != null) + { + c.ContextFlyout.ShowAt(c, true); + } + } + } + + } } }