Merge pull request #689 from SignorParabellaux/navmenu-improvements

Keyboard Navigation for NavMenu
This commit is contained in:
Dong Bin
2025-06-12 15:53:09 +08:00
committed by GitHub
3 changed files with 560 additions and 227 deletions

View File

@@ -10,30 +10,31 @@
<Setter Property="SubMenuIndent" Value="24" />
<Setter Property="Template">
<ControlTemplate TargetType="u:NavMenu">
<DockPanel LastChildFill="True">
<ContentPresenter Content="{TemplateBinding Header}" DockPanel.Dock="Top" />
<ContentPresenter Content="{TemplateBinding Footer}" DockPanel.Dock="Bottom" />
<ScrollViewer
HorizontalAlignment="Stretch"
HorizontalScrollBarVisibility="Disabled"
AllowAutoHide="True"
VerticalScrollBarVisibility="Auto">
<ScrollViewer.Styles>
<Style Selector="ScrollViewer /template/ ScrollBar">
<Setter Property="Opacity" Value="0" />
</Style>
<Style Selector="ScrollViewer:pointerover">
<Style Selector="^ /template/ ScrollBar#PART_HorizontalScrollBar">
<Setter Property="Opacity" Value="1" />
</Style>
<Style Selector="^ /template/ ScrollBar#PART_VerticalScrollBar">
<Setter Property="Opacity" Value="1" />
</Style>
</Style>
</ScrollViewer.Styles>
<ItemsPresenter ItemsPanel="{TemplateBinding ItemsPanel}" />
</ScrollViewer>
</DockPanel>
<Grid RowDefinitions="Auto, *, Auto">
<ContentPresenter Content="{TemplateBinding Header}" />
<ScrollViewer
Grid.Row="1"
HorizontalAlignment="Stretch"
HorizontalScrollBarVisibility="Disabled"
AllowAutoHide="True"
VerticalScrollBarVisibility="Auto">
<ScrollViewer.Styles>
<Style Selector="ScrollViewer /template/ ScrollBar">
<Setter Property="Opacity" Value="0" />
</Style>
<Style Selector="ScrollViewer:pointerover">
<Style Selector="^ /template/ ScrollBar#PART_HorizontalScrollBar">
<Setter Property="Opacity" Value="1" />
</Style>
<Style Selector="^ /template/ ScrollBar#PART_VerticalScrollBar">
<Setter Property="Opacity" Value="1" />
</Style>
</Style>
</ScrollViewer.Styles>
<ItemsPresenter Name="PART_ItemsPresenter" ItemsPanel="{TemplateBinding ItemsPanel}" />
</ScrollViewer>
<ContentPresenter Grid.Row="2" Content="{TemplateBinding Footer}" />
</Grid>
</ControlTemplate>
</Setter>
<Style Selector="^:not(:horizontal-collapsed)">
@@ -182,6 +183,12 @@
<Style Selector="^ /template/ ContentPresenter#PART_HeaderPresenter:pointerover">
<Setter Property="Foreground" Value="{DynamicResource ListBoxItemPointeroverForeground}" />
</Style>
<Style Selector="^:focus /template/ Border#PART_Border">
<Setter Property="Background" Value="{DynamicResource ListBoxItemPointeroverBackground}" />
</Style>
<Style Selector="^:focus /template/ ContentPresenter#PART_HeaderPresenter">
<Setter Property="Foreground" Value="{DynamicResource ListBoxItemPointeroverForeground}" />
</Style>
<Style Selector="^:horizontal-collapsed:first-level">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Style Selector="^ /template/ Border#PART_Border">

View File

@@ -1,6 +1,7 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
@@ -8,13 +9,17 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.VisualTree;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
[TemplatePart(PART_ItemsPresenter, typeof(ItemsPresenter))]
[PseudoClasses(PC_HorizontalCollapsed)]
public class NavMenu : ItemsControl
public class NavMenu : ItemsControl, ICustomKeyboardNavigation
{
public const string PART_ItemsPresenter = "PART_ItemsPresenter";
public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public static readonly StyledProperty<object?> SelectedItemProperty = AvaloniaProperty.Register<NavMenu, object?>(
@@ -69,7 +74,9 @@ public class NavMenu : ItemsControl
public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent =
RoutedEvent.Register<NavMenu, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble);
private bool _updateFromUI;
private ItemsPresenter? _itemsPresenter = null;
private bool _isSelectionFromUI = false;
private bool _isNavigatingMenu = false;
static NavMenu()
{
@@ -183,6 +190,73 @@ public class NavMenu : ItemsControl
remove => RemoveHandler(SelectionChangedEvent, value);
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new NavMenuItem();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_itemsPresenter = e.NameScope.Find<ItemsPresenter>(PART_ItemsPresenter);
if (_itemsPresenter is not null)
KeyboardNavigation.SetTabNavigation(_itemsPresenter, KeyboardNavigationMode.Once);
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
TryToSelectItem(SelectedItem);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Handled) return;
var source = GetContainerFromEventSource(e.Source);
if (GetNextItem(source, e.Key) is { } target)
{
if (e.Key is Key.Up or Key.Down && source is { Level: 1 } firstLevelSource)
firstLevelSource.CloseAllOpenPopups();
e.Handled = target.Focus(NavigationMethod.Directional);
}
}
/// <summary>
/// this implementation only works in the case that only leaf menu item is allowed to select. It will be changed if we
/// introduce parent level selection in the future.
/// </summary>
/// <param name="args"></param>
private void OnSelectedItemChange(AvaloniaPropertyChangedEventArgs<object?> args)
{
var a = new SelectionChangedEventArgs(
SelectionChangedEvent,
new[] { args.OldValue.Value },
new[] { args.NewValue.Value });
if (_isSelectionFromUI)
{
RaiseEvent(a);
return;
}
var newValue = args.NewValue.Value;
if (newValue is null)
{
ClearAll();
RaiseEvent(a);
return;
}
var found = TryToSelectItem(newValue);
if (!found) ClearAll();
RaiseEvent(a);
}
private static void OnInputRegisteredAsToggle(InputElement input, AvaloniaPropertyChangedEventArgs<bool> e)
{
if (e.NewValue.Value)
@@ -200,41 +274,120 @@ public class NavMenu : ItemsControl
nav.IsHorizontalCollapsed = !collapsed;
}
protected override void OnLoaded(RoutedEventArgs e)
internal void SelectItem(NavMenuItem item, NavMenuItem parent)
{
base.OnLoaded(e);
TryToSelectItem(SelectedItem);
}
/// <summary>
/// this implementation only works in the case that only leaf menu item is allowed to select. It will be changed if we
/// introduce parent level selection in the future.
/// </summary>
/// <param name="args"></param>
private void OnSelectedItemChange(AvaloniaPropertyChangedEventArgs<object?> args)
{
var a = new SelectionChangedEventArgs(
SelectionChangedEvent,
new[] { args.OldValue.Value },
new[] { args.NewValue.Value });
if (_updateFromUI)
_isSelectionFromUI = true;
foreach (var child in LogicalChildren)
{
RaiseEvent(a);
return;
if (Equals(child, parent)) continue;
if (child is NavMenuItem navMenuItem) navMenuItem.ClearSelection();
}
var newValue = args.NewValue.Value;
if (newValue is null)
{
ClearAll();
RaiseEvent(a);
return;
}
var found = TryToSelectItem(newValue);
if (!found) ClearAll();
RaiseEvent(a);
if (item.DataContext is not null && item.DataContext != DataContext)
SelectedItem = item.DataContext;
else
SelectedItem = item;
item.BringIntoView();
_isSelectionFromUI = false;
}
private void ClearAll()
{
foreach (var child in LogicalChildren)
if (child is NavMenuItem item)
item.ClearSelection();
}
(bool handled, IInputElement? next) ICustomKeyboardNavigation.GetNext(IInputElement element, NavigationDirection direction)
{
if (direction is not NavigationDirection.Next and not NavigationDirection.Previous ||
_isNavigatingMenu ||
_itemsPresenter is null) return (false, null);
var visual = element as Visual;
if (!_itemsPresenter.IsVisualAncestorOf(visual))
{
_isNavigatingMenu = true;
var next = KeyboardNavigationHandler.GetNext(element, direction);
_isNavigatingMenu = false;
if (_itemsPresenter.IsVisualAncestorOf(next as Visual))
{
var target = IsHorizontalCollapsed
? GetRootMenuItem(GetContainerForItem(SelectedItem))
: GetUncollapsedOrTopmostMenuItem(GetContainerForItem(SelectedItem));
target ??= ContainerFromIndex(this, 0);
return (target is not null, target);
}
}
else
{
_isNavigatingMenu = true;
var next = KeyboardNavigationHandler.GetNext(_itemsPresenter, direction);
_isNavigatingMenu = false;
if (element is NavMenuItem { Level: 1 } firstLevelItem) firstLevelItem.CloseAllOpenPopups();
return (true, next);
}
return (false, null);
}
private NavMenuItem? GetNextItem(NavMenuItem? current, Key key, bool skipChildren = false)
{
if (current?.Parent is not ItemsControl parent) return null;
var index = IndexFromContainer(parent, current);
return key switch
{
Key.Up => NavigateUp(),
Key.Down => NavigateDown(),
Key.Right when !IsHorizontalCollapsed => NavigateDown(),
Key.Left or Key.Escape => parent as NavMenuItem,
Key.Right or Key.Enter => FirstChild(current),
_ => null
};
NavMenuItem? NavigateUp()
{
if (FindSibling(parent, index - 1, -1) is { } previous)
return !IsHorizontalCollapsed && !previous.IsVerticalCollapsed && previous.ItemCount > 0
? LastChild(previous)
: previous;
return IsHorizontalCollapsed ? LastChild(parent) : parent as NavMenuItem;
}
NavMenuItem? NavigateDown()
{
if (!skipChildren &&
!IsHorizontalCollapsed &&
!current.IsVerticalCollapsed &&
current.ItemCount > 0 &&
FirstChild(current) is { } firstChild) return firstChild;
if (FindSibling(parent, index + 1, 1) is { } next) return next;
if (IsHorizontalCollapsed) return FirstChild(parent);
return GetNextItem(parent as NavMenuItem, key, true);
}
static NavMenuItem? FirstChild(ItemsControl control) => FindSibling(control, 0, 1);
static NavMenuItem? LastChild(ItemsControl control) => FindSibling(control, control.ItemCount - 1, -1);
static NavMenuItem? FindSibling(ItemsControl control, int start, int step)
{
for (var i = start; i >= 0 && i < control.ItemCount; i += step)
if (ContainerFromIndex(control, i) is { IsEnabled: true, IsSeparator: false } item) return item;
return null;
}
}
private bool TryToSelectItem(object? item)
{
if (item is null) return false;
@@ -250,33 +403,6 @@ public class NavMenu : ItemsControl
return found;
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new NavMenuItem();
}
internal void SelectItem(NavMenuItem item, NavMenuItem parent)
{
_updateFromUI = true;
foreach (var child in LogicalChildren)
{
if (Equals(child, parent)) continue;
if (child is NavMenuItem navMenuItem) navMenuItem.ClearSelection();
}
if (item.DataContext is not null && item.DataContext != DataContext)
SelectedItem = item.DataContext;
else
SelectedItem = item;
item.BringIntoView();
_updateFromUI = false;
}
private IEnumerable<NavMenuItem> GetLeafMenus()
{
foreach (var child in LogicalChildren)
@@ -287,10 +413,77 @@ public class NavMenu : ItemsControl
}
}
private void ClearAll()
public NavMenuItem? GetContainerForItem(object? item)
{
foreach (var child in LogicalChildren)
if (child is NavMenuItem item)
item.ClearSelection();
if (item == null) return null;
return GetContainerForItem(this, item);
static NavMenuItem? GetContainerForItem(ItemsControl control, object item)
{
if (ContainerFromItem(control, item) is NavMenuItem container) return container;
var children = GetRealizedContainers(control);
foreach (var child in children)
if (GetContainerForItem(child, item) is { } childContainer) return childContainer;
return null;
}
}
private NavMenuItem? GetContainerFromEventSource(object? eventSource)
{
if (eventSource is not Visual visual) return null;
return visual.GetSelfAndVisualAncestors()
.OfType<NavMenuItem>()
.FirstOrDefault(i => i.RootMenu == this);
}
private static NavMenuItem? ContainerFromIndex(ItemsControl itemsControl, int index) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareContainerFromIndex(index)
: (NavMenuItem?)itemsControl.ContainerFromIndex(index);
private static NavMenuItem? ContainerFromItem(ItemsControl itemsControl, object item) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareContainerFromItem(item)
: (NavMenuItem?)itemsControl.ContainerFromItem(item);
private static int IndexFromContainer(ItemsControl itemsControl, NavMenuItem container) =>
itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareIndexFromContainer(container)
: itemsControl.IndexFromContainer(container);
private static IEnumerable<NavMenuItem> GetRealizedContainers(ItemsControl itemsControl)
{
var realizedContainers = itemsControl is NavMenuItem navMenuItem
? navMenuItem.CollapsedAwareRealizedContainers()
: itemsControl.GetRealizedContainers();
return realizedContainers.OfType<NavMenuItem>();
}
private static NavMenuItem? GetRootMenuItem(NavMenuItem? item)
{
if (item is null) return null;
return item.GetSelfAndLogicalAncestors()
.OfType<NavMenuItem>()
.FirstOrDefault(i => i.Level == 1);
}
private static NavMenuItem? GetUncollapsedOrTopmostMenuItem(NavMenuItem? item)
{
NavMenuItem? result = null;
while (item is not null)
{
var currentParent = item.Parent as NavMenuItem;
result ??= currentParent?.IsVerticalCollapsed is false ? item : null;
if (item.Level == 1) return result ?? item;
item = currentParent;
}
return null;
}
}

View File

@@ -18,7 +18,12 @@ namespace Ursa.Controls;
/// <summary>
/// Navigation Menu Item
/// </summary>
[PseudoClasses(PC_Highlighted, PC_HorizontalCollapsed, PC_VerticalCollapsed, PC_FirstLevel, PC_Selector)]
[PseudoClasses(
PC_Highlighted,
PC_HorizontalCollapsed,
PC_VerticalCollapsed,
PC_FirstLevel,
PC_Selector)]
public class NavMenuItem : HeaderedItemsControl
{
public const string PC_Highlighted = ":highlighted";
@@ -27,8 +32,6 @@ public class NavMenuItem : HeaderedItemsControl
public const string PC_VerticalCollapsed = ":vertical-collapsed";
public const string PC_Selector = ":selector";
private static readonly Point InvalidPoint = new(double.NaN, double.NaN);
public static readonly StyledProperty<object?> IconProperty = AvaloniaProperty.Register<NavMenuItem, object?>(
nameof(Icon));
@@ -72,11 +75,9 @@ public class NavMenuItem : HeaderedItemsControl
private bool _isHighlighted;
private int _level;
private Panel? _overflowPanel;
private Point _pointerDownPoint = InvalidPoint;
private bool _isPointerDown = false;
private Popup? _popup;
private NavMenu? _rootMenu;
static NavMenuItem()
{
// SelectableMixin.Attach<NavMenuItem>(IsSelectedProperty);
@@ -157,6 +158,181 @@ public class NavMenuItem : HeaderedItemsControl
set => SetValue(IsSeparatorProperty, value);
}
internal NavMenu? RootMenu { get; private set; }
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new NavMenuItem();
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
RootMenu = GetRootMenu();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
SetCurrentValue(LevelProperty, CalculateDistanceFromLogicalParent<NavMenu>(this));
_popup = e.NameScope.Find<Popup>("PART_Popup");
_overflowPanel = e.NameScope.Find<Panel>("PART_OverflowPanel");
if (RootMenu is not null)
{
this.TryBind(IconProperty, RootMenu.IconBinding);
this.TryBind(HeaderProperty, RootMenu.HeaderBinding);
this.TryBind(ItemsSourceProperty, RootMenu.SubMenuBinding);
this.TryBind(CommandProperty, RootMenu.CommandBinding);
this[!IconTemplateProperty] = RootMenu[!NavMenu.IconTemplateProperty];
this[!HeaderTemplateProperty] = RootMenu[!NavMenu.HeaderTemplateProperty];
this[!SubMenuIndentProperty] = RootMenu[!NavMenu.SubMenuIndentProperty];
this[!IsHorizontalCollapsedProperty] = RootMenu[!NavMenu.IsHorizontalCollapsedProperty];
}
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var root = ItemsPanelRoot;
if (root is OverflowStackPanel stack) stack.OverflowPanel = _overflowPanel;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Handled) return;
if (e.Key is Key.Enter)
{
if (IsSeparator)
{
e.Handled = true;
return;
}
else if (ItemCount == 0)
{
SelectAndExecute();
e.Handled = true;
return;
}
}
if (!IsHorizontalCollapsed)
{
var handler = e.Key switch
{
Key.Left => ApplyToItemOrRecursivelyIfCtrl(FocusAwareCollapseItem, e.KeyModifiers),
Key.Right => ApplyToItemOrRecursivelyIfCtrl(ExpandItem, e.KeyModifiers),
Key.Enter => ApplyToItemOrRecursivelyIfCtrl(IsVerticalCollapsed ? ExpandItem : CollapseItem, e.KeyModifiers),
Key.Subtract => FocusAwareCollapseItem,
Key.Add => ExpandItem,
Key.Divide => ApplyToSubtree(CollapseItem),
Key.Multiply => ApplyToSubtree(ExpandItem),
_ => null
};
if (handler is not null)
e.Handled = handler(this);
static bool ToggleCollapse(NavMenuItem item, bool collapse)
{
if (item.ItemCount > 0 && item.IsVerticalCollapsed != collapse)
{
item.SetCurrentValue(IsVerticalCollapsedProperty, collapse);
return true;
}
return false;
}
static bool ExpandItem(NavMenuItem item) => ToggleCollapse(item, false);
static bool CollapseItem(NavMenuItem item) => ToggleCollapse(item, true);
static bool FocusAwareCollapseItem(NavMenuItem item)
{
if (item.ItemCount > 0 && !item.IsVerticalCollapsed)
{
if (item.IsFocused)
item.SetCurrentValue(IsVerticalCollapsedProperty, true);
else
item.Focus(NavigationMethod.Directional);
return true;
}
return false;
}
static Func<NavMenuItem, bool> ApplyToItemOrRecursivelyIfCtrl(Func<NavMenuItem, bool> f, KeyModifiers keyModifiers) => keyModifiers.HasFlag(KeyModifiers.Control)
? ApplyToSubtree(f)
: f;
static Func<NavMenuItem, bool> ApplyToSubtree(Func<NavMenuItem, bool> f) => i => Subtree(i)
.ToList()
.Select(i => f(i))
.Aggregate(false, (p, c) => p || c);
static IEnumerable<NavMenuItem> Subtree(NavMenuItem item)
{
yield return item;
var children = item.LogicalChildren
.OfType<NavMenuItem>()
.SelectMany(child => Subtree(child));
foreach (var child in children) yield return child;
}
}
else if (e.Key is Key.Right or Key.Enter)
{
TogglePopup(e.Source, true, true);
}
else if (e.Key is Key.Left or Key.Escape)
{
TogglePopup(e.Source, false, false);
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (IsSeparator)
{
e.Handled = true;
return;
}
base.OnPointerPressed(e);
if (e.Handled) return;
var p = e.GetCurrentPoint(this);
if (p.Properties.PointerUpdateKind is not (PointerUpdateKind.LeftButtonPressed
or PointerUpdateKind.RightButtonPressed)) return;
if (p.Pointer.Type == PointerType.Mouse)
ActivateMenuItem(e);
else
_isPointerDown = true;
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (e.Handled || !_isPointerDown) return;
_isPointerDown = false;
if (e.InitialPressMouseButton is MouseButton.Left or MouseButton.Right)
{
var point = e.GetCurrentPoint(this);
if (new Rect(Bounds.Size).ContainsExclusive(point.Position) && e.Pointer.Type == PointerType.Touch)
ActivateMenuItem(e);
}
}
private void OnIsHorizontalCollapsedChanged(AvaloniaPropertyChangedEventArgs<bool> args)
{
if (args.NewValue.Value)
@@ -174,138 +350,39 @@ public class NavMenuItem : HeaderedItemsControl
PseudoClasses.Set(PC_FirstLevel, args.NewValue.Value == 1);
}
protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
public NavMenuItem? CollapsedAwareContainerFromIndex(int index) =>
IsHorizontalCollapsed && _overflowPanel is not null
? index >= 0 && index < _overflowPanel.Children.Count
? (NavMenuItem?)_overflowPanel.Children[index]
: null
: (NavMenuItem?)ContainerFromIndex(index);
public NavMenuItem? CollapsedAwareContainerFromItem(object item)
{
return NeedsContainer<NavMenuItem>(item, out recycleKey);
var index = Items.IndexOf(item);
return index >= 0 ? CollapsedAwareContainerFromIndex(index) : null;
}
protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
public int CollapsedAwareIndexFromContainer(NavMenuItem container) =>
IsHorizontalCollapsed && _overflowPanel is not null
? _overflowPanel.Children.IndexOf(container)
: IndexFromContainer((Control)container);
public object? CollapsedAwareItemFromContainer(NavMenuItem container)
{
return new NavMenuItem();
var index = CollapsedAwareIndexFromContainer(container);
return index >= 0 && index < Items.Count ? Items[index] : null;
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
_rootMenu = GetRootMenu();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
SetCurrentValue(LevelProperty, CalculateDistanceFromLogicalParent<NavMenu>(this));
_popup = e.NameScope.Find<Popup>("PART_Popup");
_overflowPanel = e.NameScope.Find<Panel>("PART_OverflowPanel");
if (_rootMenu is not null)
{
this.TryBind(IconProperty, _rootMenu.IconBinding);
this.TryBind(HeaderProperty, _rootMenu.HeaderBinding);
this.TryBind(ItemsSourceProperty, _rootMenu.SubMenuBinding);
this.TryBind(CommandProperty, _rootMenu.CommandBinding);
this[!IconTemplateProperty] = _rootMenu[!NavMenu.IconTemplateProperty];
this[!HeaderTemplateProperty] = _rootMenu[!NavMenu.HeaderTemplateProperty];
this[!SubMenuIndentProperty] = _rootMenu[!NavMenu.SubMenuIndentProperty];
this[!IsHorizontalCollapsedProperty] = _rootMenu[!NavMenu.IsHorizontalCollapsedProperty];
}
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var root = ItemsPanelRoot;
if (root is OverflowStackPanel stack) stack.OverflowPanel = _overflowPanel;
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (IsSeparator)
{
e.Handled = true;
return;
}
base.OnPointerPressed(e);
if (e.Handled) return;
var p = e.GetCurrentPoint(this);
if (p.Properties.PointerUpdateKind is not (PointerUpdateKind.LeftButtonPressed
or PointerUpdateKind.RightButtonPressed)) return;
if (p.Pointer.Type == PointerType.Mouse)
{
if (ItemCount == 0)
{
SelectItem(this);
Command?.Execute(CommandParameter);
e.Handled = true;
}
else
{
if (!IsHorizontalCollapsed)
{
SetCurrentValue(IsVerticalCollapsedProperty, !IsVerticalCollapsed);
e.Handled = true;
}
else
{
if (_popup is null || e.Source is not Visual v || _popup.IsInsidePopup(v)) return;
if (_popup.IsOpen)
_popup.Close();
else
_popup.Open();
}
}
}
else
{
_pointerDownPoint = p.Position;
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled && !double.IsNaN(_pointerDownPoint.X) &&
e.InitialPressMouseButton is MouseButton.Left or MouseButton.Right)
{
var point = e.GetCurrentPoint(this);
if (!new Rect(Bounds.Size).ContainsExclusive(point.Position) || e.Pointer.Type != PointerType.Touch) return;
if (ItemCount == 0)
{
SelectItem(this);
Command?.Execute(CommandParameter);
e.Handled = true;
}
else
{
if (!IsHorizontalCollapsed)
{
SetCurrentValue(IsVerticalCollapsedProperty, !IsVerticalCollapsed);
e.Handled = true;
}
else
{
if (_popup is null || e.Source is not Visual v || _popup.IsInsidePopup(v)) return;
if (_popup.IsOpen)
_popup.Close();
else
_popup.Open();
}
}
}
}
public IEnumerable<Control> CollapsedAwareRealizedContainers() =>
IsHorizontalCollapsed && _overflowPanel is not null
? _overflowPanel.Children
: GetRealizedContainers();
internal void SelectItem(NavMenuItem item)
{
if (item == this)
{
SetCurrentValue(IsSelectedProperty, true);
SetCurrentValue(IsHighlightedProperty, true);
}
else
{
SetCurrentValue(IsSelectedProperty, false);
SetCurrentValue(IsHighlightedProperty, true);
}
SetCurrentValue(IsSelectedProperty, item == this);
SetCurrentValue(IsHighlightedProperty, true);
if (Parent is NavMenuItem menuItem)
{
@@ -320,7 +397,7 @@ public class NavMenuItem : HeaderedItemsControl
menu.SelectItem(item, this);
}
if (_popup is not null) _popup.Close();
_popup?.Close();
}
internal void ClearSelection()
@@ -332,23 +409,40 @@ public class NavMenuItem : HeaderedItemsControl
item.ClearSelection();
}
private NavMenu? GetRootMenu()
private void SelectAndExecute()
{
var root = this.FindAncestorOfType<NavMenu>() ?? this.FindLogicalAncestorOfType<NavMenu>();
return root;
SelectItem(this);
Command?.Execute(CommandParameter);
}
private static int CalculateDistanceFromLogicalParent<T>(ILogical? logical, int @default = -1) where T : class
private void ActivateMenuItem(RoutedEventArgs e)
{
var result = 0;
while (logical != null && !(logical is T))
if (ItemCount == 0)
{
if (logical is NavMenuItem) result++;
logical = logical.LogicalParent;
SelectAndExecute();
e.Handled = true;
return;
}
return logical != null ? result : @default;
if (!IsHorizontalCollapsed)
{
SetCurrentValue(IsVerticalCollapsedProperty, !IsVerticalCollapsed);
e.Handled = true;
}
else if (_popup is not null)
{
TogglePopup(e.Source, true, !_popup.IsOpen);
}
}
private void TogglePopup(object? source, bool outsidePopup, bool open)
{
if (ItemCount > 0 &&
_popup is not null &&
source is Visual visual &&
_popup.IsInsidePopup(visual) != outsidePopup &&
_popup.IsOpen != open)
_popup.IsOpen = open;
}
internal IEnumerable<NavMenuItem> GetLeafMenus()
@@ -366,4 +460,43 @@ public class NavMenuItem : HeaderedItemsControl
foreach (var i in items) yield return i;
}
}
internal void CloseAllOpenPopups()
{
var items = GetItemsWithChildren(this).Reverse();
foreach (var item in items)
if (item._popup is { IsOpen: true } popup) popup.Close();
static IEnumerable<NavMenuItem> GetItemsWithChildren(NavMenuItem item)
{
if (item.ItemCount > 0)
{
yield return item;
var children = item.LogicalChildren
.OfType<NavMenuItem>()
.SelectMany(child => GetItemsWithChildren(child));
foreach (var child in children) yield return child;
}
}
}
private NavMenu? GetRootMenu()
{
var root = this.FindAncestorOfType<NavMenu>() ?? this.FindLogicalAncestorOfType<NavMenu>();
return root;
}
private static int CalculateDistanceFromLogicalParent<T>(ILogical? logical, int @default = -1) where T : class
{
var result = 0;
while (logical is not null and not T)
{
if (logical is NavMenuItem) result++;
logical = logical.LogicalParent;
}
return logical is not null ? result : @default;
}
}