WPF本地化应用中自定义RoutedCommand输入手势未本地化问题咨询
自定义RoutedCommand键盘快捷键本地化问题的原因与解决方案
问题原因
WPF内置的ApplicationCommands之所以能自动将键盘修饰符(比如Ctrl)本地化对应语言的表述(德语下是Strg),是因为这些命令的输入手势是通过**KeyGesture实例**绑定的,WPF会自动调用KeyGestureConverter,根据当前应用的UI文化从系统内置的本地化资源中加载修饰符的对应文本。
而你的自定义RoutedCommand如果是直接在XAML里用字符串硬编码Gesture="Ctrl+...",这个字符串不会经过任何本地化转换,所以会原样显示Ctrl+...,无法适配目标语言。
无需硬编码的本地化实现方法
核心思路是:给自定义命令绑定**KeyGesture实例**(而非字符串),让WPF自动处理本地化转换。下面提供两种常用实现方式:
方式一:后台代码定义命令与输入手势
在静态类中创建自定义命令,并直接添加KeyGesture实例到命令的InputGestures集合:
using System.Windows.Input; namespace YourAppNamespace { public static class CustomCommands { public static readonly RoutedCommand Save = new RoutedCommand( "Save", typeof(CustomCommands)); static CustomCommands() { // 添加KeyGesture实例,而非硬编码字符串 Save.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control)); } } }
方式二:XAML资源中定义命令与输入手势
直接在XAML资源里声明RoutedCommand,并通过<KeyGesture>元素指定键和修饰符:
<Window.Resources> <RoutedCommand x:Key="CustomSaveCommand" Text="Save"> <RoutedCommand.InputGestures> <!-- 使用KeyGesture元素,而非字符串属性 --> <KeyGesture Key="S" Modifiers="Control"/> </RoutedCommand.InputGestures> </RoutedCommand> </Window.Resources>
完整示例代码
1. 主窗口XAML(MainWindow.xaml)
<Window x:Class="YourAppNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:YourAppNamespace" Title="MainWindow" Height="450" Width="800"> <Window.CommandBindings> <!-- 绑定自定义命令的执行逻辑 --> <CommandBinding Command="{x:Static local:CustomCommands.Save}" Executed="SaveCommand_Executed"/> </Window.CommandBindings> <DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Header="File"> <!-- 自定义命令菜单项 --> <MenuItem Command="{x:Static local:CustomCommands.Save}" Header="Save"/> <!-- 内置命令对比参考 --> <MenuItem Command="ApplicationCommands.Save" Header="Built-in Save"/> </MenuItem> </Menu> <Grid/> </DockPanel> </Window>
2. 后台代码(MainWindow.xaml.cs)
using System.Windows; using System.Windows.Input; namespace YourAppNamespace { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e) { // 这里添加你的保存逻辑 MessageBox.Show("自定义保存命令执行!"); } } }
3. 设置UI文化(App.xaml.cs)
确保应用启动时设置正确的目标UI文化,让WPF加载对应的本地化资源:
using System.Globalization; using System.Threading; using System.Windows; namespace YourAppNamespace { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { // 设置德语UI文化 Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE"); base.OnStartup(e); } } }
运行后你会发现,自定义命令的快捷键文本会和内置命令一样,自动显示为德语的Strg+S,无需手动硬编码翻译。
内容的提问来源于stack exchange,提问作者alxnull




