Merge pull request #105 from irihitech/nav

Nav Menu Refactoring Step 1.
This commit is contained in:
Dong Bin
2024-02-14 21:09:55 +08:00
committed by GitHub
15 changed files with 1220 additions and 8 deletions

View File

@@ -0,0 +1,222 @@
<ResourceDictionary
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:Ursa.Themes.Semi.Converters"
xmlns:u="https://irihi.tech/ursa">
<!-- Add Resources Here -->
<converters:NavMenuMarginConverter x:Key="NavMarginConverter" />
<ControlTheme x:Key="{x:Type u:NavMenu}" TargetType="u:NavMenu">
<Setter Property="Grid.IsSharedSizeScope" Value="True" />
<Setter Property="SubMenuIndent" Value="24" />
<Setter Property="Template">
<ControlTemplate TargetType="u:NavMenu">
<DockPanel LastChildFill="True">
<ContentPresenter Content="{TemplateBinding Header}" DockPanel.Dock="Top"></ContentPresenter>
<ContentPresenter Content="{TemplateBinding Footer}" DockPanel.Dock="Bottom"></ContentPresenter>
<ScrollViewer HorizontalAlignment="Center" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<ItemsPresenter ItemsPanel="{TemplateBinding ItemsPanel}" />
</ScrollViewer>
</DockPanel>
</ControlTemplate>
</Setter>
<Style Selector="^:horizontal-collapsed">
<Setter Property="Width" Value="{x:Static x:Double.NaN}"></Setter>
<Setter Property="HorizontalAlignment" Value="Left"></Setter>
</Style>
</ControlTheme>
<ControlTemplate x:Key="DefaultNavMenuItemTemplate" TargetType="u:NavMenuItem">
<Grid RowDefinitions="Auto, *">
<Border
Name="PART_Border"
Grid.Row="0"
MinHeight="32"
Cursor="Hand"
Background="{TemplateBinding u:NavMenuItem.Background}"
CornerRadius="4">
<Grid
Name="PART_RootGrid"
HorizontalAlignment="Stretch"
VerticalAlignment="Center">
<Grid.Margin>
<MultiBinding Converter="{StaticResource NavMarginConverter}">
<Binding Path="SubMenuIndent" RelativeSource="{RelativeSource TemplatedParent}" />
<Binding Path="Level" RelativeSource="{RelativeSource TemplatedParent}" />
<Binding Path="IsHorizontalCollapsed" RelativeSource="{RelativeSource TemplatedParent}" />
</MultiBinding>
</Grid.Margin>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Icon" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" SharedSizeGroup="Expander" />
</Grid.ColumnDefinitions>
<ContentPresenter
Name="PART_IconPresenter"
Padding="8"
HorizontalAlignment="Left"
Background="Transparent"
Content="{Binding Icon, RelativeSource={RelativeSource TemplatedParent}}"
ContentTemplate="{Binding IconTemplate, RelativeSource={RelativeSource TemplatedParent}}" />
<ContentPresenter
Name="PART_HeaderPresenter"
Grid.Column="1"
Padding="0,8"
Background="Transparent"
Content="{Binding Header, RelativeSource={RelativeSource TemplatedParent}}"
ContentTemplate="{Binding HeaderTemplate, RelativeSource={RelativeSource TemplatedParent}}" />
<PathIcon
Name="PART_ExpanderIcon"
Grid.Column="2"
Width="8"
Height="8"
Margin="12,0"
Data="{DynamicResource NavigationMenuItemExpandIconGlyph}"
Foreground="{DynamicResource NavigationMenuItemExpandIconForeground}">
<PathIcon.Transitions>
<Transitions>
<TransformOperationsTransition Property="RenderTransform" Duration="0.1" />
</Transitions>
</PathIcon.Transitions>
</PathIcon>
<Popup
Name="PART_Popup"
Grid.Column="0"
IsLightDismissEnabled="True"
Placement="RightEdgeAlignedTop"
PlacementTarget="{Binding #PART_Border}">
<Border
Margin="{DynamicResource NavigationMenuItemFlyoutMargin}"
Padding="{DynamicResource MenuFlyoutPadding}"
HorizontalAlignment="Stretch"
Background="{DynamicResource MenuFlyoutBackground}"
BorderBrush="{DynamicResource MenuFlyoutBorderBrush}"
BorderThickness="{DynamicResource MenuFlyoutBorderThickness}"
BoxShadow="{DynamicResource MenuFlyoutBorderBoxShadow}"
CornerRadius="{DynamicResource MenuFlyoutCornerRadius}">
<StackPanel Name="PART_OverflowPanel" />
</Border>
</Popup>
</Grid>
</Border>
<ItemsPresenter
Name="PART_ItemsPresenter"
Grid.Row="1"
Margin="0,4,0,0"
VerticalAlignment="Top"
Grid.IsSharedSizeScope="True"
ItemsPanel="{Binding ItemsPanel, RelativeSource={RelativeSource TemplatedParent}}"
RenderTransformOrigin="0.5,0">
<ItemsPresenter.Transitions>
<Transitions>
<DoubleTransition Property="Height" Duration="0.1" />
<TransformOperationsTransition Property="RenderTransform" Duration="0.1" />
</Transitions>
</ItemsPresenter.Transitions>
</ItemsPresenter>
</Grid>
</ControlTemplate>
<ControlTheme x:Key="{x:Type u:NavMenuItem}" TargetType="u:NavMenuItem">
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
<Setter Property="ItemsPanel">
<ItemsPanelTemplate>
<u:OverflowStackPanel />
</ItemsPanelTemplate>
</Setter>
<Setter Property="Template" Value="{StaticResource DefaultNavMenuItemTemplate}" />
<Style Selector="^:selected">
<Setter Property="Background" Value="{DynamicResource NavigationMenuItemSelectedBackground}" />
<Style Selector="^:pointerover">
<Setter Property="Background" Value="{DynamicResource NavigationMenuItemSelectedBackground}" />
</Style>
</Style>
<Style Selector="^:vertical-collapsed /template/ ItemsPresenter#PART_ItemsPresenter">
<Setter Property="Height" Value="0" />
<Setter Property="RenderTransform" Value="scale(1,0)" />
</Style>
<Style Selector="^:vertical-collapsed /template/ PathIcon#PART_ExpanderIcon">
<Setter Property="RenderTransform" Value="rotate(180deg)" />
</Style>
<Style Selector="^:empty /template/ PathIcon#PART_ExpanderIcon">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^ /template/ Border#PART_Border:pointerover">
<Setter Property="Background" Value="{DynamicResource NavigationMenuItemPointeroverBackground}" />
</Style>
<Style Selector="^:horizontal-collapsed:first-level">
<Setter Property="HorizontalAlignment" Value="Left"></Setter>
<Style Selector="^ /template/ Border#PART_Border">
<Setter Property="ToolTip.Tip" Value="{Binding Header, RelativeSource={RelativeSource TemplatedParent}}" />
<Setter Property="ToolTip.ShowDelay" Value="0" />
<Setter Property="HorizontalAlignment" Value="Left" />
</Style>
<Style Selector="^ /template/ Border#PART_Border:pointerover">
<Setter Property="Background" Value="{DynamicResource NavigationMenuItemPointeroverBackground}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_IconPresenter">
<Setter Property="Grid.ColumnSpan" Value="3" />
<Setter Property="Margin" Value="0 8"></Setter>
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_HeaderPresenter">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^ /template/ PathIcon#PART_ExpanderIcon">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^ /template/ ItemsPresenter#PART_ItemsPresenter">
<Setter Property="IsVisible" Value="False" />
</Style>
<Style Selector="^ /template/ Grid#PART_RootGrid">
<Setter Property="HorizontalAlignment" Value="Left" />
</Style>
</Style>
<Style Selector="^:horizontal-collapsed:not(:first-level)">
<Style Selector="^ /template/ PathIcon#PART_ExpanderIcon">
<Setter Property="RenderTransform" Value="rotate(-90deg)" />
</Style>
</Style>
<Style Selector="^[IsSeparator=True]">
<Setter Property="Template">
<ControlTemplate>
<StackPanel Cursor="No" Name="PART_RootPanel" Margin="{DynamicResource NavigationMenuSeparatorMargin}">
<ContentPresenter
Name="PART_HeaderPresenter"
Margin="{DynamicResource NavigationMenuSeparatorHeaderMargin}"
HorizontalAlignment="Left"
Content="{TemplateBinding Header}"
ContentTemplate="{TemplateBinding HeaderTemplate}"
Foreground="{DynamicResource TextBlockQuaternaryForeground}"
IsVisible="{TemplateBinding Header, Converter={x:Static ObjectConverters.IsNotNull}}">
<ContentPresenter.Styles>
<Style Selector="TextBlock">
<Setter Property="FontSize" Value="{DynamicResource NavigationMenuSeparatorHeaderFontSize}" />
</Style>
</ContentPresenter.Styles>
</ContentPresenter>
<Rectangle
Name="PART_SeparatorBorder"
Height="{DynamicResource NavigationMenuSeparatorBorderHeight}"
Margin="{DynamicResource NavigationMenuSeparatorBorderMargin}"
HorizontalAlignment="Stretch"
Fill="{DynamicResource SemiColorBorder}" />
</StackPanel>
</ControlTemplate>
</Setter>
<Style Selector="^:horizontal-collapsed:first-level">
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Style Selector="^ /template/ ContentPresenter#PART_HeaderPresenter">
<Setter Property="IsVisible" Value="False"></Setter>
</Style>
<Style Selector="^ /template/ Rectangle#PART_SeparatorBorder">
<Setter Property="HorizontalAlignment" Value="Center"></Setter>
<Setter Property="Width" Value="12"></Setter>
</Style>
</Style>
</Style>
</ControlTheme>
</ResourceDictionary>

View File

@@ -18,6 +18,7 @@
<ResourceInclude Source="Loading.axaml" />
<ResourceInclude Source="MessageBox.axaml" />
<ResourceInclude Source="Navigation.axaml" />
<ResourceInclude Source="NavMenu.axaml" />
<ResourceInclude Source="NumericUpDown.axaml" />
<ResourceInclude Source="Pagination.axaml" />
<ResourceInclude Source="RangeSlider.axaml" />

View File

@@ -0,0 +1,17 @@
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
namespace Ursa.Themes.Semi.Converters;
public class NavMenuMarginConverter: IMultiValueConverter
{
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
{
if (values[0] is double indent && values[1] is int level && values[2] is bool b)
{
return b ? new Thickness() : new Thickness(indent * (level-1), 0, 0, 0);
}
return AvaloniaProperty.UnsetValue;
}
}

View File

@@ -5,6 +5,7 @@ using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Media;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
@@ -75,13 +76,7 @@ public class TwoTonePathIcon: TemplatedControl
ForegroundProperty,
ActiveForegroundProperty,
ActiveStrokeBrushProperty);
IsActiveProperty.Changed.AddClassHandler<TwoTonePathIcon, bool>((o, e) => o.OnIsActiveChanged(e));
}
private void OnIsActiveChanged(AvaloniaPropertyChangedEventArgs<bool> args)
{
var newValue = args.NewValue.Value;
PseudoClasses.Set(PC_Active, newValue);
PropertyToPseudoClassMixin.Attach<TwoTonePathIcon>(IsActiveProperty, PC_Active);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)

View File

@@ -0,0 +1,276 @@
using System.Diagnostics;
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
[PseudoClasses(PC_HorizontalCollapsed)]
public class NavMenu: ItemsControl
{
public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public static readonly StyledProperty<object?> SelectedItemProperty = AvaloniaProperty.Register<NavMenu, object?>(
nameof(SelectedItem), defaultBindingMode: BindingMode.TwoWay);
public object? SelectedItem
{
get => GetValue(SelectedItemProperty);
set => SetValue(SelectedItemProperty, value);
}
public static readonly StyledProperty<IBinding?> IconBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(IconBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? IconBinding
{
get => GetValue(IconBindingProperty);
set => SetValue(IconBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> HeaderBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(HeaderBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? HeaderBinding
{
get => GetValue(HeaderBindingProperty);
set => SetValue(HeaderBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> SubMenuBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(SubMenuBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? SubMenuBinding
{
get => GetValue(SubMenuBindingProperty);
set => SetValue(SubMenuBindingProperty, value);
}
public static readonly StyledProperty<IBinding?> CommandBindingProperty = AvaloniaProperty.Register<NavMenu, IBinding?>(
nameof(CommandBinding));
[AssignBinding]
[InheritDataTypeFromItems(nameof(ItemsSource))]
public IBinding? CommandBinding
{
get => GetValue(CommandBindingProperty);
set => SetValue(CommandBindingProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> HeaderTemplateProperty = AvaloniaProperty.Register<NavMenu, IDataTemplate?>(
nameof(HeaderTemplate));
/// <summary>
/// Header Template is used for MenuItem headers, not menu header.
/// </summary>
public IDataTemplate? HeaderTemplate
{
get => GetValue(HeaderTemplateProperty);
set => SetValue(HeaderTemplateProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> IconTemplateProperty = AvaloniaProperty.Register<NavMenu, IDataTemplate?>(
nameof(IconTemplate));
public IDataTemplate? IconTemplate
{
get => GetValue(IconTemplateProperty);
set => SetValue(IconTemplateProperty, value);
}
public static readonly StyledProperty<double> SubMenuIndentProperty = AvaloniaProperty.Register<NavMenu, double>(
nameof(SubMenuIndent));
public double SubMenuIndent
{
get => GetValue(SubMenuIndentProperty);
set => SetValue(SubMenuIndentProperty, value);
}
public static readonly StyledProperty<bool> IsHorizontalCollapsedProperty = AvaloniaProperty.Register<NavMenu, bool>(
nameof(IsHorizontalCollapsed));
public bool IsHorizontalCollapsed
{
get => GetValue(IsHorizontalCollapsedProperty);
set => SetValue(IsHorizontalCollapsedProperty, value);
}
public static readonly StyledProperty<object?> HeaderProperty =
HeaderedContentControl.HeaderProperty.AddOwner<NavMenu>();
public object? Header
{
get => GetValue(HeaderProperty);
set => SetValue(HeaderProperty, value);
}
public static readonly StyledProperty<object?> FooterProperty = AvaloniaProperty.Register<NavMenu, object?>(
nameof(Footer));
public object? Footer
{
get => GetValue(FooterProperty);
set => SetValue(FooterProperty, value);
}
public static readonly AttachedProperty<bool> CanToggleProperty =
AvaloniaProperty.RegisterAttached<NavMenu, InputElement, bool>("CanToggle");
public static void SetCanToggle(InputElement obj, bool value) => obj.SetValue(CanToggleProperty, value);
public static bool GetCanToggle(InputElement obj) => obj.GetValue(CanToggleProperty);
public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<NavMenu, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble);
public event EventHandler<SelectionChangedEventArgs>? SelectionChanged
{
add => AddHandler(SelectionChangedEvent, value);
remove => RemoveHandler(SelectionChangedEvent, value);
}
static NavMenu()
{
SelectedItemProperty.Changed.AddClassHandler<NavMenu, object?>((o, e) => o.OnSelectedItemChange(e));
PropertyToPseudoClassMixin.Attach<NavMenu>(IsHorizontalCollapsedProperty, PC_HorizontalCollapsed);
CanToggleProperty.Changed.AddClassHandler<InputElement, bool>(OnInputRegisteredAsToggle);
}
private static void OnInputRegisteredAsToggle(InputElement input, AvaloniaPropertyChangedEventArgs<bool> e)
{
if (e.NewValue.Value)
{
input.AddHandler(PointerPressedEvent, OnElementToggle);
}
else
{
input.RemoveHandler(PointerPressedEvent, OnElementToggle);
}
}
private static void OnElementToggle(object? sender, RoutedEventArgs args)
{
if (sender is not InputElement input) return;
var nav = input.FindLogicalAncestorOfType<NavMenu>();
if(nav is null) return;
bool collapsed = nav.IsHorizontalCollapsed;
nav.IsHorizontalCollapsed = !collapsed;
}
/// <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)
{
SelectionChangedEventArgs a = new SelectionChangedEventArgs(
SelectionChangedEvent,
new [] { args.OldValue.Value },
new [] { args.NewValue.Value });
if (_updateFromUI)
{
RaiseEvent(a);
return;
}
var newValue = args.NewValue.Value;
if (newValue is null)
{
ClearAll();
RaiseEvent(a);
return;
}
var leaves = GetLeafMenus();
bool found = false;
foreach (var leaf in leaves)
{
if (leaf == newValue || leaf.DataContext == newValue)
{
leaf.SelectItem(leaf);
found = true;
}
}
if (!found)
{
ClearAll();
}
RaiseEvent(a);
}
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();
}
private bool _updateFromUI;
internal void SelectItem(NavMenuItem item, NavMenuItem parent)
{
_updateFromUI = true;
foreach (var child in LogicalChildren)
{
if (child == parent)
{
continue;
}
if (child is NavMenuItem navMenuItem)
{
navMenuItem.ClearSelection();
}
}
if (item.DataContext is not null && item.DataContext != this.DataContext)
{
SelectedItem = item.DataContext;
}
else
{
SelectedItem = item;
}
item.BringIntoView();
_updateFromUI = false;
}
private IEnumerable<NavMenuItem> GetLeafMenus()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var leafs = item.GetLeafMenus();
foreach (var leaf in leafs)
{
yield return leaf;
}
}
}
}
private void ClearAll()
{
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
item.ClearSelection();
}
}
}
}

View File

@@ -0,0 +1,352 @@
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
using Irihi.Avalonia.Shared.Helpers;
namespace Ursa.Controls;
/// <summary>
/// Navigation Menu Item
/// </summary>
[PseudoClasses(PC_Highlighted, PC_HorizontalCollapsed, PC_VerticalCollapsed, PC_FirstLevel, PC_Selector)]
public class NavMenuItem: HeaderedItemsControl
{
public const string PC_Highlighted = ":highlighted";
public const string PC_FirstLevel = ":first-level";
public const string PC_HorizontalCollapsed = ":horizontal-collapsed";
public const string PC_VerticalCollapsed = ":vertical-collapsed";
public const string PC_Selector = ":selector";
private NavMenu? _rootMenu;
private Panel? _popupPanel;
private Popup? _popup;
private Panel? _overflowPanel;
public static readonly StyledProperty<object?> IconProperty = AvaloniaProperty.Register<NavMenuItem, object?>(
nameof(Icon));
public object? Icon
{
get => GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public static readonly StyledProperty<IDataTemplate?> IconTemplateProperty = AvaloniaProperty.Register<NavMenuItem, IDataTemplate?>(
nameof(IconTemplate));
public IDataTemplate? IconTemplate
{
get => GetValue(IconTemplateProperty);
set => SetValue(IconTemplateProperty, value);
}
public static readonly StyledProperty<ICommand?> CommandProperty = Button.CommandProperty.AddOwner<NavMenuItem>();
public ICommand? Command
{
get => GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public static readonly StyledProperty<object?> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<NavMenuItem>();
public object? CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
public static readonly StyledProperty<bool> IsSelectedProperty =
SelectingItemsControl.IsSelectedProperty.AddOwner<NavMenuItem>();
public bool IsSelected
{
get => GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent = RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>("IsSelectedChanged", RoutingStrategies.Bubble);
private bool _isHighlighted;
public static readonly DirectProperty<NavMenuItem, bool> IsHighlightedProperty =
AvaloniaProperty.RegisterDirect<NavMenuItem, bool>(
nameof(IsHighlighted), o => o.IsHighlighted, (o, v) => o.IsHighlighted = v,
defaultBindingMode: BindingMode.TwoWay);
public bool IsHighlighted
{
get => _isHighlighted;
private set => SetAndRaise(IsHighlightedProperty, ref _isHighlighted, value);
}
public static readonly StyledProperty<bool> IsHorizontalCollapsedProperty =
NavMenu.IsHorizontalCollapsedProperty.AddOwner<NavMenuItem>();
public bool IsHorizontalCollapsed
{
get => GetValue(IsHorizontalCollapsedProperty);
set => SetValue(IsHorizontalCollapsedProperty, value);
}
public static readonly StyledProperty<bool> IsVerticalCollapsedProperty = AvaloniaProperty.Register<NavMenuItem, bool>(
nameof(IsVerticalCollapsed));
public bool IsVerticalCollapsed
{
get => GetValue(IsVerticalCollapsedProperty);
set => SetValue(IsVerticalCollapsedProperty, value);
}
public static readonly StyledProperty<double> SubMenuIndentProperty =
NavMenu.SubMenuIndentProperty.AddOwner<NavMenuItem>();
public double SubMenuIndent
{
get => GetValue(SubMenuIndentProperty);
set => SetValue(SubMenuIndentProperty, value);
}
internal static readonly DirectProperty<NavMenuItem, int> LevelProperty = AvaloniaProperty.RegisterDirect<NavMenuItem, int>(
nameof(Level), o => o.Level, (o, v) => o.Level = v);
private int _level;
internal int Level
{
get => _level;
set => SetAndRaise(LevelProperty, ref _level, value);
}
public static readonly StyledProperty<bool> IsSeparatorProperty = AvaloniaProperty.Register<NavMenuItem, bool>(
nameof(IsSeparator));
public bool IsSeparator
{
get => GetValue(IsSeparatorProperty);
set => SetValue(IsSeparatorProperty, value);
}
static NavMenuItem()
{
// SelectableMixin.Attach<NavMenuItem>(IsSelectedProperty);
PressedMixin.Attach<NavMenuItem>();
LevelProperty.Changed.AddClassHandler<NavMenuItem, int>((item, args) => item.OnLevelChange(args));
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsHighlightedProperty, PC_Highlighted);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsHorizontalCollapsedProperty, PC_HorizontalCollapsed);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsVerticalCollapsedProperty, PC_VerticalCollapsed);
PropertyToPseudoClassMixin.Attach<NavMenuItem>(IsSelectedProperty, ":selected", IsSelectedChangedEvent);
IsHorizontalCollapsedProperty.Changed.AddClassHandler<NavMenuItem, bool>((item, args) =>
item.OnIsHorizontalCollapsedChanged(args));
}
private void OnIsHorizontalCollapsedChanged(AvaloniaPropertyChangedEventArgs<bool> args)
{
if (args.NewValue.Value)
{
if (this.ItemsPanelRoot is OverflowStackPanel s)
{
s.MoveChildrenToOverflowPanel();
}
}
else
{
if (this.ItemsPanelRoot is OverflowStackPanel s)
{
s.MoveChildrenToMainPanel();
}
}
}
private void OnLevelChange(AvaloniaPropertyChangedEventArgs<int> args)
{
PseudoClasses.Set(PC_FirstLevel, args.NewValue.Value == 1);
}
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)
{
if (_rootMenu.IconBinding is not null)
{
this[!IconProperty] = _rootMenu.IconBinding;
}
if (_rootMenu.HeaderBinding is not null)
{
this[!HeaderProperty] = _rootMenu.HeaderBinding;
}
if (_rootMenu.SubMenuBinding is not null)
{
this[!ItemsSourceProperty] = _rootMenu.SubMenuBinding;
}
if (_rootMenu.CommandBinding is not null)
{
this[!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 = this.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 (this.ItemCount == 0)
{
SelectItem(this);
}
else
{
if (!IsHorizontalCollapsed)
{
SetCurrentValue(IsVerticalCollapsedProperty, !IsVerticalCollapsed);
}
else
{
if (_popup is not null)
{
if (_popup.IsOpen)
{
_popup.Close();
}
else
{
_popup.Open();
}
}
}
}
Command?.Execute(CommandParameter);
e.Handled = true;
}
internal void SelectItem(NavMenuItem item)
{
if (item == this)
{
SetCurrentValue(IsSelectedProperty, true);
SetCurrentValue(IsHighlightedProperty, true);
}
else
{
SetCurrentValue(IsSelectedProperty, false);
SetCurrentValue(IsHighlightedProperty, true);
}
if (this.Parent is NavMenuItem menuItem)
{
menuItem.SelectItem(item);
var items = menuItem.LogicalChildren.OfType<NavMenuItem>();
foreach (var child in items)
{
if (child != this)
{
child.ClearSelection();
}
}
}
else if (this.Parent is NavMenu menu)
{
menu.SelectItem(item, this);
}
}
internal void ClearSelection()
{
SetCurrentValue(IsHighlightedProperty, false);
SetCurrentValue(IsSelectedProperty, false);
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
item.ClearSelection();
}
}
}
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 != null && !(logical is T))
{
if (logical is NavMenuItem)
{
result++;
}
logical = logical.LogicalParent;
}
return logical != null ? result : @default;
}
internal IEnumerable<NavMenuItem> GetLeafMenus()
{
if (this.ItemCount == 0)
{
yield return this;
yield break;
}
foreach (var child in LogicalChildren)
{
if (child is NavMenuItem item)
{
var items = item.GetLeafMenus();
foreach (var i in items)
{
yield return i;
}
}
}
}
}

View File

@@ -0,0 +1,30 @@
using Avalonia.Controls;
namespace Ursa.Controls;
public class OverflowStackPanel: StackPanel
{
public Panel? OverflowPanel { get; set; }
public void MoveChildrenToOverflowPanel()
{
var children = this.Children.ToList();
foreach (var child in children)
{
Children.Remove(child);
OverflowPanel?.Children.Add(child);
}
}
public void MoveChildrenToMainPanel()
{
var children = this.OverflowPanel?.Children.ToList();
if (children != null && children.Count > 0)
{
foreach (var child in children)
{
OverflowPanel?.Children.Remove(child);
Children.Add(child);
}
}
}
}

View File

@@ -14,7 +14,7 @@
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Irihi.Avalonia.Shared" Version="0.1.1" />
<PackageReference Include="Irihi.Avalonia.Shared" Version="0.1.2" />
</ItemGroup>
</Project>