-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathMenuItem.cs
More file actions
949 lines (830 loc) · 33.8 KB
/
MenuItem.cs
File metadata and controls
949 lines (830 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia.Automation;
using Avalonia.Automation.Peers;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Reactive;
namespace Avalonia.Controls
{
/// <summary>
/// A menu item control.
/// </summary>
[TemplatePart("PART_Popup", typeof(Popup))]
[PseudoClasses(":separator", ":radio", ":toggle", ":checked", ":icon", ":open", ":pressed", ":selected")]
public class MenuItem : HeaderedSelectingItemsControl, IMenuItem, ISelectable, ICommandSource, IClickableControl, IRadioButton
{
private EventHandler? _canExecuteChangeHandler = default;
private EventHandler CanExecuteChangedHandler => _canExecuteChangeHandler ??= new(CanExecuteChanged);
/// <summary>
/// Defines the <see cref="Command"/> property.
/// </summary>
public static readonly StyledProperty<ICommand?> CommandProperty =
Button.CommandProperty.AddOwner<MenuItem>(new(enableDataValidation: true));
/// <summary>
/// Defines the <see cref="HotKey"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture?> HotKeyProperty =
HotKeyManager.HotKeyProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="CommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object?> CommandParameterProperty =
Button.CommandParameterProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="Icon"/> property.
/// </summary>
public static readonly StyledProperty<object?> IconProperty =
AvaloniaProperty.Register<MenuItem, object?>(nameof(Icon));
/// <summary>
/// Defines the <see cref="InputGesture"/> property.
/// </summary>
public static readonly StyledProperty<KeyGesture?> InputGestureProperty =
AvaloniaProperty.Register<MenuItem, KeyGesture?>(nameof(InputGesture));
/// <summary>
/// Defines the <see cref="IsSubMenuOpen"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsSubMenuOpenProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(IsSubMenuOpen));
/// <summary>
/// Defines the <see cref="StaysOpenOnClick"/> property.
/// </summary>
public static readonly StyledProperty<bool> StaysOpenOnClickProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(StaysOpenOnClick));
/// <summary>
/// Defines the <see cref="ToggleType"/> property.
/// </summary>
public static readonly StyledProperty<MenuItemToggleType> ToggleTypeProperty =
AvaloniaProperty.Register<MenuItem, MenuItemToggleType>(nameof(ToggleType));
/// <summary>
/// Defines the <see cref="IsChecked"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsCheckedProperty =
AvaloniaProperty.Register<MenuItem, bool>(nameof(IsChecked));
/// <summary>
/// Defines the <see cref="GroupName"/> property.
/// </summary>
public static readonly StyledProperty<string?> GroupNameProperty =
RadioButton.GroupNameProperty.AddOwner<MenuItem>();
/// <summary>
/// Defines the <see cref="Click"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClickEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(
nameof(Click),
RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerEnteredItem"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> PointerEnteredItemEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(
nameof(PointerEnteredItem),
RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="PointerExitedItem"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> PointerExitedItemEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(
nameof(PointerExitedItem),
RoutingStrategies.Bubble);
/// <summary>
/// Defines the <see cref="SubmenuOpened"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> SubmenuOpenedEvent =
RoutedEvent.Register<MenuItem, RoutedEventArgs>(
nameof(SubmenuOpened),
RoutingStrategies.Bubble);
/// <summary>
/// The default value for the <see cref="ItemsControl.ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<Panel?> DefaultPanel =
new(() => new StackPanel());
private bool _commandCanExecute = true;
private bool _commandBindingError;
private Popup? _popup;
private KeyGesture? _hotkey;
private bool _isEmbeddedInMenu;
/// <summary>
/// Initializes static members of the <see cref="MenuItem"/> class.
/// </summary>
static MenuItem()
{
SelectableMixin.Attach<MenuItem>(IsSelectedProperty);
PressedMixin.Attach<MenuItem>();
FocusableProperty.OverrideDefaultValue<MenuItem>(true);
ItemsPanelProperty.OverrideDefaultValue<MenuItem>(DefaultPanel);
ClickEvent.AddClassHandler<MenuItem>((x, e) => x.OnClick(e));
SubmenuOpenedEvent.AddClassHandler<MenuItem>((x, e) => x.OnSubmenuOpened(e));
AutomationProperties.IsOffscreenBehaviorProperty.OverrideDefaultValue<MenuItem>(IsOffscreenBehavior.FromClip);
AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<MenuItem>(OnAccessKeyPressed);
}
public MenuItem()
{
// HACK: This nasty but it's all WPF's fault. Grid uses an inherited attached
// property to store SharedSizeGroup state, except property inheritance is done
// down the logical tree. In this case, the control which is setting
// Grid.IsSharedSizeScope="True" is not in the logical tree. Instead of fixing
// the way Grid stores shared size state, the developers of WPF just created a
// binding of the internal state of the visual parent to the menu item. We don't
// have much choice but to do the same for now unless we want to refactor Grid,
// which I honestly am not brave enough to do right now. Here's the same hack in
// the WPF codebase:
//
// https://github.com/dotnet/wpf/blob/89537909bdf36bc918e88b37751add46a8980bb0/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/MenuItem.cs#L2126-L2141
//
// In addition to the hack from WPF, we also make sure to return null when we have
// no parent. If we don't do this, inheritance falls back to the logical tree,
// causing the shared size scope in the parent MenuItem to be used, breaking
// menu layout.
var parentSharedSizeScope = this.GetObservable(VisualParentProperty)
.Select(x =>
{
var parent = x as Control;
return parent?.GetObservable(DefinitionBase.PrivateSharedSizeScopeProperty) ??
Observable.Return<DefinitionBase.SharedSizeScope?>(null);
})
.Switch();
this.Bind(DefinitionBase.PrivateSharedSizeScopeProperty, parentSharedSizeScope);
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/> without a submenu is clicked.
/// </summary>
public event EventHandler<RoutedEventArgs>? Click
{
add => AddHandler(ClickEvent, value);
remove => RemoveHandler(ClickEvent, value);
}
/// <summary>
/// Occurs when the pointer enters a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerEntered"/> event for menu items.
/// </remarks>
public event EventHandler<RoutedEventArgs>? PointerEnteredItem
{
add => AddHandler(PointerEnteredItemEvent, value);
remove => RemoveHandler(PointerEnteredItemEvent, value);
}
/// <summary>
/// Raised when the pointer leaves a menu item.
/// </summary>
/// <remarks>
/// A bubbling version of the <see cref="InputElement.PointerExited"/> event for menu items.
/// </remarks>
public event EventHandler<RoutedEventArgs>? PointerExitedItem
{
add => AddHandler(PointerExitedItemEvent, value);
remove => RemoveHandler(PointerExitedItemEvent, value);
}
/// <summary>
/// Occurs when a <see cref="MenuItem"/>'s submenu is opened.
/// </summary>
public event EventHandler<RoutedEventArgs>? SubmenuOpened
{
add => AddHandler(SubmenuOpenedEvent, value);
remove => RemoveHandler(SubmenuOpenedEvent, value);
}
/// <summary>
/// Gets or sets the command associated with the menu item.
/// </summary>
public ICommand? Command
{
get => GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
/// <summary>
/// Gets or sets an <see cref="KeyGesture"/> associated with this control
/// </summary>
public KeyGesture? HotKey
{
get => GetValue(HotKeyProperty);
set => SetValue(HotKeyProperty, value);
}
/// <summary>
/// Gets or sets the parameter to pass to the <see cref="Command"/> property of a
/// <see cref="MenuItem"/>.
/// </summary>
public object? CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
/// <summary>
/// Gets or sets the icon that appears in a <see cref="MenuItem"/>.
/// </summary>
public object? Icon
{
get => GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
/// <summary>
/// Gets or sets the input gesture that will be displayed in the menu item.
/// </summary>
/// <remarks>
/// Setting this property does not cause the input gesture to be handled by the menu item,
/// it simply displays the gesture text in the menu.
/// </remarks>
public KeyGesture? InputGesture
{
get => GetValue(InputGestureProperty);
set => SetValue(InputGestureProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="MenuItem"/> is currently selected.
/// </summary>
public bool IsSelected
{
get => GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}
/// <summary>
/// Gets or sets a value that indicates whether the submenu of the <see cref="MenuItem"/> is
/// open.
/// </summary>
public bool IsSubMenuOpen
{
get => GetValue(IsSubMenuOpenProperty);
set => SetValue(IsSubMenuOpenProperty, value);
}
bool IMenuItem.IsSubMenuOpen
{
get => IsSubMenuOpen;
set => SetCurrentValue(IsSubMenuOpenProperty, value);
}
/// <summary>
/// Gets or sets a value that indicates the submenu that this <see cref="MenuItem"/> is
/// within should not close when this item is clicked.
/// </summary>
public bool StaysOpenOnClick
{
get => GetValue(StaysOpenOnClickProperty);
set => SetValue(StaysOpenOnClickProperty, value);
}
bool IMenuItem.StaysOpenOnClick
{
get => StaysOpenOnClick;
set => SetCurrentValue(StaysOpenOnClickProperty, value);
}
/// <summary>
/// Gets toggle type of the menu item.
/// </summary>
public MenuItemToggleType ToggleType
{
get => GetValue(ToggleTypeProperty);
set => SetValue(ToggleTypeProperty, value);
}
/// <summary>
/// Gets or sets if menu item is checked when <see cref="ToggleType"/> is
/// <see cref="MenuItemToggleType.CheckBox"/> or <see cref="MenuItemToggleType.Radio"/>.
/// </summary>
public bool IsChecked
{
get => GetValue(IsCheckedProperty);
set => SetValue(IsCheckedProperty, value);
}
bool IMenuItem.IsChecked
{
get => IsChecked;
set => SetCurrentValue(IsCheckedProperty, value);
}
bool IRadioButton.IsChecked
{
get => IsChecked;
set => SetCurrentValue(IsCheckedProperty, value);
}
/// <summary>
/// Gets menu item group name when <see cref="ToggleType"/> is <see cref="MenuItemToggleType.Radio"/>.
/// </summary>
public string? GroupName
{
get => GetValue(GroupNameProperty);
set => SetValue(GroupNameProperty, value);
}
/// <summary>
/// Gets or sets a value that indicates whether the <see cref="MenuItem"/> has a submenu.
/// </summary>
public bool HasSubMenu => !Classes.Contains(":empty");
/// <summary>
/// Gets a value that indicates whether the <see cref="MenuItem"/> is a top-level main menu item.
/// </summary>
public bool IsTopLevel => Parent is Menu;
/// <inheritdoc/>
bool IMenuItem.IsPointerOverSubMenu => _popup?.IsPointerOverPopup ?? false;
/// <inheritdoc/>
IMenuElement? IMenuItem.Parent => Parent as IMenuElement;
protected override bool IsEnabledCore => base.IsEnabled && (HasSubMenu || _commandCanExecute);
/// <inheritdoc/>
bool IMenuElement.MoveSelection(NavigationDirection direction, bool wrap) => MoveSelection(direction, wrap);
/// <inheritdoc/>
IMenuItem? IMenuElement.SelectedItem
{
get
{
var index = SelectedIndex;
return (index != -1) ?
(IMenuItem?)ContainerFromIndex(index) :
null;
}
set => SelectedIndex = value is Control c ? IndexFromContainer(c) : -1;
}
/// <inheritdoc/>
IEnumerable<IMenuItem> IMenuElement.SubItems => LogicalChildren.OfType<IMenuItem>();
private IMenuInteractionHandler? MenuInteractionHandler => this.FindLogicalAncestorOfType<MenuBase>()?.InteractionHandler;
/// <summary>
/// Opens the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to true.
/// </remarks>
public void Open() => SetCurrentValue(IsSubMenuOpenProperty, true);
/// <summary>
/// Closes the submenu.
/// </summary>
/// <remarks>
/// This has the same effect as setting <see cref="IsSubMenuOpen"/> to false.
/// </remarks>
public void Close() => SetCurrentValue(IsSubMenuOpenProperty, false);
/// <inheritdoc/>
void IMenuItem.RaiseClick() => RaiseEvent(new RoutedEventArgs(ClickEvent));
protected internal override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new MenuItem();
}
protected internal override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
if (item is MenuItem or Separator)
{
recycleKey = null;
return false;
}
recycleKey = DefaultRecycleKey;
return true;
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!_isEmbeddedInMenu)
{
//Normally the Menu's IMenuInteractionHandler is sending the click events for us
//However when the item is not embedded into a menu we need to send them ourselves.
RaiseEvent(new RoutedEventArgs(ClickEvent));
}
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
if (_hotkey != null) // Control attached again, set Hotkey to create a hotkey manager for this control
{
SetCurrentValue(HotKeyProperty, _hotkey);
}
base.OnAttachedToLogicalTree(e);
(var command, var parameter) = (Command, CommandParameter);
if (command is not null)
{
command.CanExecuteChanged += CanExecuteChangedHandler;
}
TryUpdateCanExecute(command, parameter);
var parent = Parent;
while (parent is MenuItem)
{
parent = parent.Parent;
}
_isEmbeddedInMenu = parent?.FindLogicalAncestorOfType<IMenu>(true) != null;
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
TryUpdateCanExecute();
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
// This will cause the hotkey manager to dispose the observer and the reference to this control
if (HotKey != null)
{
_hotkey = HotKey;
SetCurrentValue(HotKeyProperty, null);
}
base.OnDetachedFromLogicalTree(e);
if (Command != null)
{
Command.CanExecuteChanged -= CanExecuteChangedHandler;
}
}
/// <summary>
/// Invoked when an unhandled <see cref="ClickEvent"/> reaches an element in its
/// route that is derived from this class. Implement this method to add class handling
/// for this event.
/// </summary>
/// <param name="e">Data about the event.</param>
protected virtual void OnClick(RoutedEventArgs e)
{
(var command, var parameter) = (Command, CommandParameter);
if (!e.Handled && command is not null && command.CanExecute(parameter) == true)
{
command.Execute(parameter);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
ItemsControlFromItemContainer(this)?.UpdateSelectionFromEvent(this, e);
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
// Don't handle here: let event bubble up to menu.
}
/// <inheritdoc/>
protected override void OnPointerEntered(PointerEventArgs e)
{
base.OnPointerEntered(e);
RaiseEvent(new RoutedEventArgs(PointerEnteredItemEvent));
}
/// <inheritdoc/>
protected override void OnPointerExited(PointerEventArgs e)
{
base.OnPointerExited(e);
RaiseEvent(new RoutedEventArgs(PointerExitedItemEvent));
}
/// <summary>
/// Invoked when an unhandled <see cref="SubmenuOpenedEvent"/> reaches an element in its
/// route that is derived from this class. Implement this method to add class handling
/// for this event.
/// </summary>
/// <param name="e">Data about the event.</param>
protected virtual void OnSubmenuOpened(RoutedEventArgs e)
{
var menuItem = e.Source as MenuItem;
if (menuItem != null && menuItem.Parent == this)
{
foreach (var child in ((IMenuItem)this).SubItems)
{
if (child != menuItem && child.IsSubMenuOpen)
{
child.IsSubMenuOpen = false;
}
}
}
}
/// <inheritdoc/>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
if (_popup != null)
{
_popup.Opened -= PopupOpened;
_popup.Closed -= PopupClosed;
_popup.DependencyResolver = null;
}
_popup = e.NameScope.Find<Popup>("PART_Popup");
if (_popup != null)
{
_popup.DependencyResolver = DependencyResolver.Instance;
_popup.Opened += PopupOpened;
_popup.Closed += PopupClosed;
}
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new MenuItemAutomationPeer(this);
}
// TODO: This is confusing for some ppl. Need to think about alternatives here.
protected override void UpdateDataValidation(
AvaloniaProperty property,
BindingValueType state,
Exception? error)
{
base.UpdateDataValidation(property, state, error);
if (property == CommandProperty)
{
_commandBindingError = state == BindingValueType.BindingError;
if (_commandBindingError && _commandCanExecute)
{
_commandCanExecute = false;
UpdateIsEffectivelyEnabled();
}
}
}
/// <summary>
/// Closes all submenus of the menu item.
/// </summary>
private void CloseSubmenus()
{
foreach (var child in ((IMenuItem)this).SubItems)
{
child.IsSubMenuOpen = false;
}
}
/// <summary>
/// Called when the <see cref="Command"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
var newCommand = e.NewValue as ICommand;
if (e.Sender is MenuItem menuItem)
{
if (((ILogical)menuItem).IsAttachedToLogicalTree)
{
if (e.OldValue is ICommand oldCommand)
{
oldCommand.CanExecuteChanged -= menuItem.CanExecuteChangedHandler;
}
if (newCommand is not null)
{
newCommand.CanExecuteChanged += menuItem.CanExecuteChangedHandler;
}
}
menuItem.TryUpdateCanExecute(newCommand, menuItem.CommandParameter);
}
}
private static void OnAccessKeyPressed(MenuItem sender, AccessKeyPressedEventArgs e)
{
if (e is not { Handled: false, Target: null })
return;
e.Target = sender;
e.Handled = true;
}
/// <summary>
/// Called when the <see cref="CommandParameter"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void CommandParameterChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is MenuItem menuItem)
{
(var command, var parameter) = (menuItem.Command, e.NewValue);
menuItem.TryUpdateCanExecute(command, parameter);
}
}
/// <summary>
/// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void CanExecuteChanged(object? sender, EventArgs e)
{
TryUpdateCanExecute();
}
/// <summary>
/// Tries to evaluate CanExecute value of a Command if menu is opened
/// </summary>
private void TryUpdateCanExecute()
{
TryUpdateCanExecute(Command, CommandParameter);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private void TryUpdateCanExecute(ICommand? command, object? parameter)
{
if (command == null)
{
_commandCanExecute = !_commandBindingError;
UpdateIsEffectivelyEnabled();
return;
}
//Perf optimization - only raise CanExecute event if the menu is open
if (!((ILogical)this).IsAttachedToLogicalTree ||
Parent is MenuItem { IsSubMenuOpen: false })
{
return;
}
var canExecute = command.CanExecute(parameter);
if (canExecute != _commandCanExecute)
{
_commandCanExecute = canExecute;
UpdateIsEffectivelyEnabled();
}
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == HeaderProperty)
{
HeaderChanged(change);
}
else if (change.Property == IconProperty)
{
IconChanged(change);
}
else if (change.Property == IsSelectedProperty)
{
IsSelectedChanged(change);
}
else if (change.Property == IsSubMenuOpenProperty)
{
SubMenuOpenChanged(change);
}
else if (change.Property == CommandProperty)
{
CommandChanged(change);
}
else if (change.Property == CommandParameterProperty)
{
CommandParameterChanged(change);
}
else if (change.Property == IsCheckedProperty)
{
IsCheckedChanged(change);
}
else if (change.Property == ToggleTypeProperty)
{
ToggleTypeChanged(change);
}
else if (change.Property == GroupNameProperty)
{
GroupNameChanged(change);
}
else if (change.Property == ItemCountProperty)
{
// A menu item with no sub-menu is effectively disabled if its command binding
// failed: this means that the effectively enabled state depends on whether the
// number of items in the menu is 0 or not.
var (o, n) = change.GetOldAndNewValue<int>();
if (o == 0 || n == 0)
UpdateIsEffectivelyEnabled();
}
}
/// <summary>
/// Called when the <see cref="GroupName"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void GroupNameChanged(AvaloniaPropertyChangedEventArgs e)
{
(MenuInteractionHandler as DefaultMenuInteractionHandler)?.OnGroupOrTypeChanged(this, e.GetOldValue<string>());
}
/// <summary>
/// Called when the <see cref="ToggleType"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void ToggleTypeChanged(AvaloniaPropertyChangedEventArgs e)
{
var newValue = e.GetNewValue<MenuItemToggleType>();
PseudoClasses.Set(":radio", newValue == MenuItemToggleType.Radio);
PseudoClasses.Set(":toggle", newValue == MenuItemToggleType.CheckBox);
(MenuInteractionHandler as DefaultMenuInteractionHandler)?.OnGroupOrTypeChanged(this, GroupName);
}
/// <summary>
/// Called when the <see cref="IsChecked"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IsCheckedChanged(AvaloniaPropertyChangedEventArgs e)
{
var newValue = e.GetNewValue<bool>();
PseudoClasses.Set(":checked", newValue);
if (newValue)
{
(MenuInteractionHandler as DefaultMenuInteractionHandler)?.OnCheckedChanged(this);
}
}
/// <summary>
/// Called when the <see cref="HeaderedSelectingItemsControl.Header"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void HeaderChanged(AvaloniaPropertyChangedEventArgs e)
{
var (oldValue, newValue) = e.GetOldAndNewValue<object?>();
if (Equals(newValue, "-"))
{
PseudoClasses.Add(":separator");
Focusable = false;
}
else if (Equals(oldValue, "-"))
{
PseudoClasses.Remove(":separator");
Focusable = true;
}
}
/// <summary>
/// Called when the <see cref="Icon"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IconChanged(AvaloniaPropertyChangedEventArgs e)
{
var (oldValue, newValue) = e.GetOldAndNewValue<object?>();
if (oldValue is { })
{
if (oldValue is ILogical oldLogical)
{
LogicalChildren.Remove(oldLogical);
}
PseudoClasses.Remove(":icon");
}
if (newValue is { })
{
if (newValue is ILogical newLogical)
{
LogicalChildren.Add(newLogical);
}
PseudoClasses.Add(":icon");
}
}
/// <summary>
/// Called when the <see cref="IsSelected"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void IsSelectedChanged(AvaloniaPropertyChangedEventArgs e)
{
var parentMenu = Parent as Menu;
if ((bool)e.NewValue! && (parentMenu is null || parentMenu.IsOpen))
{
Focus();
}
}
/// <summary>
/// Called when the <see cref="IsSubMenuOpen"/> property changes.
/// </summary>
/// <param name="e">The property change event.</param>
private void SubMenuOpenChanged(AvaloniaPropertyChangedEventArgs e)
{
var value = (bool)e.NewValue!;
if (value)
{
foreach (var item in ItemsView.OfType<MenuItem>())
{
item.TryUpdateCanExecute();
}
RaiseEvent(new RoutedEventArgs(SubmenuOpenedEvent));
SetCurrentValue(IsSelectedProperty, true);
PseudoClasses.Add(":open");
}
else
{
CloseSubmenus();
SelectedIndex = -1;
PseudoClasses.Remove(":open");
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is opened.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupOpened(object? sender, EventArgs e)
{
// If we're using overlay popups, there's a chance we need to do a layout pass before
// the child items are added to the visual tree. If we don't do this here, then
// selection breaks.
if (Presenter?.IsAttachedToVisualTree == false)
UpdateLayout();
var selected = SelectedIndex;
if (selected != -1)
{
var container = ContainerFromIndex(selected);
container?.Focus();
}
}
/// <summary>
/// Called when the submenu's <see cref="Popup"/> is closed.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void PopupClosed(object? sender, EventArgs e)
{
SelectedItem = null;
}
void ICommandSource.CanExecuteChanged(object sender, EventArgs e) => CanExecuteChangedHandler(sender, e);
void IClickableControl.RaiseClick()
{
if (IsEffectivelyEnabled)
{
RaiseEvent(new RoutedEventArgs(ClickEvent));
}
}
/// <summary>
/// A dependency resolver which returns a <see cref="MenuItemAccessKeyHandler"/>.
/// </summary>
private class DependencyResolver : IAvaloniaDependencyResolver
{
/// <summary>
/// Gets the default instance of <see cref="DependencyResolver"/>.
/// </summary>
public static readonly DependencyResolver Instance = new DependencyResolver();
/// <summary>
/// Gets a service of the specified type.
/// </summary>
/// <param name="serviceType">The service type.</param>
/// <returns>A service of the requested type.</returns>
public object? GetService(Type serviceType)
{
if (serviceType == typeof(IAccessKeyHandler))
{
return new MenuItemAccessKeyHandler();
}
else
{
return AvaloniaLocator.Current.GetService(serviceType);
}
}
}
}
}