I am trying to create a localizable WPF menu bar with menu items that have keyboard shortcuts - not accelerator keys/mnemonics (usually shown as underlined characters that can be pressed to directly select a menu item when the menu is already open), but keyboard shortcuts (usually combinations of Ctrl + another key) that are displayed right-aligned next to the menu item header.
I am using the MVVM pattern for my application, meaning that I avoid placing any code in code-behind wherever possible and have my view-models (that I assign to the DataContext
properties) provide implementations of the ICommand
interface that are used by controls in my views.
As a base for reproducing the issue, here is some minimal source code for an application as described:
Window1.xaml
<Window x:Class="MenuShortcutTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MenuShortcutTest" Height="300" Width="300"> <Menu> <MenuItem Header="{Binding MenuHeader}"> <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/> </MenuItem> </Menu> </Window>
Window1.xaml.cs
using System; using System.Windows; namespace MenuShortcutTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); this.DataContext = new MainViewModel(); } } }
MainViewModel.cs
using System; using System.Windows; using System.Windows.Input; namespace MenuShortcutTest { public class MainViewModel { public string MenuHeader { get { // in real code: load this string from localization return "Menu"; } } public string DoSomethingHeader { get { // in real code: load this string from localization return "Do Something"; } } private class DoSomethingCommand : ICommand { public DoSomethingCommand(MainViewModel owner) { if (owner == null) { throw new ArgumentNullException("owner"); } this.owner = owner; } private readonly MainViewModel owner; public event EventHandler CanExecuteChanged; public void Execute(object parameter) { // in real code: do something meaningful with the view-model MessageBox.Show(owner.GetType().FullName); } public bool CanExecute(object parameter) { return true; } } private ICommand doSomething; public ICommand DoSomething { get { if (doSomething == null) { doSomething = new DoSomethingCommand(this); } return doSomething; } } } }
The WPF MenuItem
class has an InputGestureText
property, but as described in SO questions such as this, this, this and this, that is purely cosmetic and has no effect whatsoever on what shortcuts are actually processed by the application.
SO questions like this and this point out that the command should be linked with a KeyBinding
in the InputBindings
list of the window. While that enables the functionality, it does not automatically display the shortcut with the menu item. Window1.xaml changes as follows:
<Window x:Class="MenuShortcutTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MenuShortcutTest" Height="300" Width="300"> <Window.InputBindings> <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/> </Window.InputBindings> <Menu> <MenuItem Header="{Binding MenuHeader}"> <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/> </MenuItem> </Menu> </Window>
I have tried manually setting the InputGestureText
property in addition, making Window1.xaml look like this:
<Window x:Class="MenuShortcutTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MenuShortcutTest" Height="300" Width="300"> <Window.InputBindings> <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/> </Window.InputBindings> <Menu> <MenuItem Header="{Binding MenuHeader}"> <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}" InputGestureText="Ctrl+D"/> </MenuItem> </Menu> </Window>
This does display the shortcut, but is not a viable solution for obvious reasons:
I have looked into creating an IValueConverter
to use for binding the InputGestureText
property to the InputBindings
list of the window (there might be more than one KeyBinding
in the InputBindings
list, or none at all, so there is no specific KeyBinding
instance that I could bind to (if KeyBinding
even lends itself to being a binding target)). This appears to me like the most desirable solution, because it is very flexible and at the same time very clean (it does not require a plethora of declarations in various places), but on the one hand, InputBindingCollection
does not implement INotifyCollectionChanged
, thus the binding would not be updated when shortcuts are replaced, and on the other hand, I did not manage to provide the converter with a reference to my view-model in a tidy manner (which it would need to access the localization data). What is more, InputBindings
is not a dependency property, so I cannot bind that to a common source (such as a list of input bindings located in the view-model) that the ItemGestureText
property could be bound to, as well.
Now, many resources (this question, that question, this thread, that question and that thread point out that RoutedCommand
and RoutedUICommand
contain a built-in InputGestures
property and imply that key bindings from that property are automatically displayed in menu items.
However, using either of those ICommand
implementations seems to open a new can of worms, as their Execute
and CanExecute
methods are not virtual and thus cannot be overridden in subclasses to fill in the desired functionality. The only way to provide that seems to be declaring a CommandBinding
in XAML (shown e.g. here or here) that connects a command with an event handler - however, that event handler would then be located in the code-behind, thus violating the MVVM architecture described above.
Trying nonetheless, this means turning most of the aforementioned structure inside-out (which also kind of implies that I need to make my mind up on how to eventually solve the issue in my current, comparably early stage of development):
Window1.xaml
<Window x:Class="MenuShortcutTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MenuShortcutTest" Title="MenuShortcutTest" Height="300" Width="300"> <Window.CommandBindings> <CommandBinding Command="{x:Static local:DoSomethingCommand.Instance}" Executed="CommandBinding_Executed"/> </Window.CommandBindings> <Menu> <MenuItem Header="{Binding MenuHeader}"> <MenuItem Header="{Binding DoSomethingHeader}" Command="{x:Static local:DoSomethingCommand.Instance}"/> </MenuItem> </Menu> </Window>
Window1.xaml.cs
using System; using System.Windows; namespace MenuShortcutTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); this.DataContext = new MainViewModel(); } void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) { ((MainViewModel)DataContext).DoSomething(); } } }
MainViewModel.cs
using System; using System.Windows; using System.Windows.Input; namespace MenuShortcutTest { public class MainViewModel { public string MenuHeader { get { // in real code: load this string from localization return "Menu"; } } public string DoSomethingHeader { get { // in real code: load this string from localization return "Do Something"; } } public void DoSomething() { // in real code: do something meaningful with the view-model MessageBox.Show(this.GetType().FullName); } } }
DoSomethingCommand.cs
using System; using System.Windows.Input; namespace MenuShortcutTest { public class DoSomethingCommand : RoutedCommand { public DoSomethingCommand() { this.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Control)); } private static Lazy<DoSomethingCommand> instance = new Lazy<DoSomethingCommand>(); public static DoSomethingCommand Instance { get { return instance.Value; } } } }
For the same reason (RoutedCommand.Execute
and such being non-virtual), I do not know how to subclass RoutedCommand
in a way to create a RelayCommand
like the one used in an answer to this question based on RoutedCommand
, so I do not have to make the detour over the InputBindings
of the window - while explicitly reimplementing the methods from ICommand
in a RoutedCommand
subclass feels like I might be breaking something.
What is more, while the shortcut is automatically displayed with this method as configured in the RoutedCommand
, it does not seem to get automatically localized. My understanding is that adding
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-de"); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
to the MainWindow
constructor should make sure that localizable strings supplied by the framework should be taken from the German CultureInfo
- however, Ctrl
does not change to Strg
, so unless I am mistaken about how to set the CultureInfo
for framework-supplied strings, this method is not viable anyway if I expect the displayed shortcut to be correctly localized.
Now, I am aware that KeyGesture
allows me to specify a custom display string for the keyboard shortcut, but not only is the RoutedCommand
-derived DoSomethingCommand
class disjoint from all of my instances (from where I could get in touch with the loaded localization) due to the way CommandBinding
has to be linked with a command in XAML, the respective DisplayString
property is read-only, so there would be no way to change it when another localization is loaded at runtime.
This leaves me with the option to manually dig through the menu tree (EDIT: for the sake of clarification, no code here because I am not asking for this and I know how to do this) and the InputBindings
list of the window to check which commands have any KeyBinding
instances associated with them, and which menu items are linked to any of those commands, so that I can manually set the InputGestureText
of each of the respective menu items to reflect the first (or preferred, by whichever metric I want to use here) keyboard shortcut. And this procedure would have to be repeated every time I think the key bindings may have changed. However, this seems like an extremely tedious workaround for something that is essentially a basic feature of a menu bar GUI, so I'm convinced it cannot be the "correct" way to do this.
What is the right way to automatically display a keyboard shortcut that is configured to work for WPF MenuItem
instances?
EDIT: All of the other questions I found dealt with how a KeyBinding
/KeyGesture
could be used to actually enable the functionality visually implied by InputGestureText
, without explaining how to automatically link the two aspects in the described situation. The only somewhat promising question that I found was this, but it has not received any answers in over two years.
ALT+SPACEBAR Opens the shortcut menu for the active window.
Assigning a shortcut key to a Start menu item. Click once within the Shortcut Key box. Press the letter or number you want to use for your shortcut key. Windows automatically adds "Ctrl+Alt+" to the beginning of the character you press.
I'll start with the warning. It can happen that you will need not only customizable hot keys but the menu itself. So think twice before using InputBindings
statically.
There is one more caution concerning InputBindings
: they imply that command is tied to the element in window's visual tree. Sometimes you need global hot keys not connected with any particular window.
The above said means that you can make it another way and implement your own application wide gestures processing with correct routing to corresponding commands (don't forget to use weak references to commands).
Nonetheless the idea of gesture aware commands is the same.
public class CommandWithHotkey : ICommand { public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { MessageBox.Show("It Worked!"); } public KeyGesture Gesture { get; set; } public string GestureText { get { return Gesture.GetDisplayStringForCulture(CultureInfo.CurrentUICulture); } } public string Text { get; set; } public event EventHandler CanExecuteChanged; public CommandWithHotkey() { Text = "Execute Me"; Gesture = new KeyGesture(Key.K, ModifierKeys.Control); } }
Simple View Model:
public class ViewModel { public ICommand Command { get; set; } public ViewModel() { Command = new CommandWithHotkey(); } }
Window:
<Window x:Class="CommandsWithHotKeys.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:commandsWithHotKeys="clr-namespace:CommandsWithHotKeys" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <commandsWithHotKeys:ViewModel/> </Window.DataContext> <Window.InputBindings> <KeyBinding Command="{Binding Command}" Key ="{Binding Command.Gesture.Key}" Modifiers="{Binding Command.Gesture.Modifiers}"></KeyBinding> </Window.InputBindings> <Grid> <Menu HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="Auto"> <MenuItem Header="Test"> <MenuItem InputGestureText="{Binding Command.GestureText}" Header="{Binding Command.Text}" Command="{Binding Command}"> </MenuItem> </MenuItem> </Menu> </Grid> </Window>
Sure, you should somehow load the gestures information from configuration and then init commands with the data.
The next step is keystokes like in VS: Ctrl+K,Ctrl+D, quick search gives this SO question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With