Skip to content

Instantly share code, notes, and snippets.

@lmadhavan
Created July 12, 2021 04:55
Show Gist options
  • Save lmadhavan/4f56a403bc8fbbda342f41e2657fc0a3 to your computer and use it in GitHub Desktop.
Save lmadhavan/4f56a403bc8fbbda342f41e2657fc0a3 to your computer and use it in GitHub Desktop.
WinUI KeyboardAccelerator workaround
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);
}
}
}
@rcg-wae
Copy link

rcg-wae commented Apr 16, 2024

Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment