Source: http://expression.microsoft.com/zh-cn/library/system.windows.input.routedcommand(printer).aspx
cs code:
namespace NameSpace { public partial class MainForm : Window {... public static RoutedCommand CustomRoutedCommandZoomIn = new RoutedCommand(); public static RoutedCommand CustomRoutedCommandZoomOut = new RoutedCommand(); private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { Control target = e.Source as Control; if (target != null) { e.CanExecute = true; } else { e.CanExecute = false; } } private void MenuItemZoomIn_Click(object sender, RoutedEventArgs e) { // Do zoom in } private void MenuItemZoomOut_Click(object sender, RoutedEventArgs e) { // Do zoom out }
xaml:
<Window ..... xmlns:mynamespace="clr-namespace:NameSpace" .....> <Window.CommandBindings> <CommandBinding Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomIn}" CanExecute="CommandBinding_CanExecute" Executed="MenuItemZoomIn_Click"/> <CommandBinding Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomOut}" CanExecute="CommandBinding_CanExecute" Executed="MenuItemZoomOut_Click"/> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomIn}" Key="I" Modifiers="Ctrl"></KeyBinding> <KeyBinding Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomOut}" Key="O" Modifiers="Ctrl"></KeyBinding> </Window.InputBindings> ... <MenuItem Header="Zoom _In" InputGestureText="Ctrl+I" Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomIn}"></MenuItem> <MenuItem Header="Zoom _Out" InputGestureText="Ctrl+O" Command="{x:Static mynamespace:MainForm.CustomRoutedCommandZoomOut}"></MenuItem> ... </Window>
Click or shortcuts work well now.
If you haveany better solution please let me know.
Thanks