简体   繁体   中英

Localized input gesture text in WPF

I have a custom RoutedCommand with an input key gesture that is called in a menu item in a localized app. I discovered that the text displayed as keyboard shortcut for my own command is not localized to German (displayed as "Ctrl+..."), while the built in ApplicationCommands' key modifiers are translated to German (displayed as "Strg+...").

The result looks like this:

它的样子

This is the xaml code:

<ContextMenu>
    <MenuItem Header="Edit" Command="local:MyWindow.MyCommand"/>
    <MenuItem Header="Save" Command="Save"/>
</ContextMenu>

Why is this? How can I localize own commands (preferebly without hardcoding the translated modifiers)?

Just to finally close this question:

As it seems, the built-in commands use some internal lookup to get localized strings for their input gestures. Eg the method for the ApplicationCommands looks like this:

https://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Input/Command/ApplicationCommands.cs,343

The only way I found that doesn't require manually adding resources for all input gestures is to convert the WPF keys to WinForms keys and create a display string there:

static Keys ToWinFormsKeys(Key key, ModifierKeys modifiers)
{
    Keys keys = (Keys)KeyInterop.VirtualKeyFromKey(key);
    if ((modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
        keys |= Keys.Alt;
    if ((modifiers & ModifierKeys.Control) == ModifierKeys.Control)
        keys |= Keys.Control;
    if ((modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
        keys |= Keys.Shift;
    return keys;
}

static KeyGesture CreateGesture(Key key, ModifierKeys modifiers)
{
    Keys formsKeys = ToWinFormsKeys(key, modifiers);
    string display = wFormsKeyConv.ConvertToString(formsKeys);
    return new KeyGesture(key, modifiers, display);
}

Now, the above example could be changed to this for the desired behaviour:

MyCommand.InputGestures.Add(CreateGesture(Key.E, ModifierKeys.Control));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM