Create a Custom Command in WPF
1.
public static RoutedCommand SwitchCommand = new RoutedCommand();
private bool isOn = false;//track the light
//Build the project will allow us to add a reference to the command in xaml
2.
xmlns:local=”clr-namespace:xxxxx”
….
3.
<MenuItem Header=”xxx” Command=”local:Window1.SwitchCommand”/>
4.
create custom CommandBindings for the command
<Window.CommandBindings>
<CommandBinding Command=”local:Window1.SwitchCommand” CanExecute=”CommandBinding_CanExecute” Executed=”CommandBinding_Executed”
</Window.CommandBindings>
5.
<Window.InputBinding>
<KeyBinding Key=”s” Command=”local:xxx” Modifiers=”Ctrl”>
</Window.InputBinding>
6.
realize the same function in code as in XAML:
<Window ….Loaded=”Window_Loaded”/>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
CommandBinding cmdB = new CommandBinding(SwitchCommand, CommandBinding_Executed, CommandBinding_CanExecute);
this.CommandBindings.Add(cmdB);
btnSwitch.Command=SwitchCommand;
KeyGesture keyG = new KeyGesture(Key.S, ModifierKeys.Control);
InputBind inputB = new InputBinding(SwitchCommand, keyG);
this.InputBindings.Add(inputB);
}

浙公网安备 33010602011771号