Created
July 12, 2021 04:55
-
-
Save lmadhavan/4f56a403bc8fbbda342f41e2657fc0a3 to your computer and use it in GitHub Desktop.
WinUI KeyboardAccelerator workaround
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class KeyboardAcceleratorWorkaround | |
{ | |
public static void CreateShadowAccelerators(this MenuBar menuBar, UIElement target) | |
{ | |
foreach (var menu in menuBar.Items) | |
{ | |
ProcessItems(menu.Items, target); | |
} | |
} | |
private static void ProcessItems(IList<MenuFlyoutItemBase> items, UIElement target) | |
{ | |
foreach (var item in items) | |
{ | |
if (item is MenuFlyoutSubItem i) | |
{ | |
ProcessItems(i.Items, target); | |
} | |
else if (item is MenuFlyoutItem fi) | |
{ | |
ProcessItem(fi, target); | |
} | |
} | |
} | |
private static void ProcessItem(MenuFlyoutItem fi, UIElement target) | |
{ | |
foreach (var accel in fi.KeyboardAccelerators) | |
{ | |
var shadowAccel = new KeyboardAccelerator | |
{ | |
Modifiers = accel.Modifiers, | |
Key = accel.Key | |
}; | |
shadowAccel.Invoked += (s, e) => | |
{ | |
if (fi.Command.CanExecute(fi.CommandParameter)) | |
{ | |
fi.Command.Execute(fi.CommandParameter); | |
} | |
e.Handled = true; | |
}; | |
target.KeyboardAccelerators.Add(shadowAccel); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!