WPF Concepts—Executing Commands with Input Gestures
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| .NET Articles |
| © 2007 Sams Publishing |
Executing Commands with Input Gestures
Using the Help command in such a simple dialog may seem like overkill when a simple event handler for Click would do, but the command has provided an extra benefit (other than localized text): automatic binding to a keyboard shortcut.
Applications typically invoke their version of help when the user presses the F1 key. Sure enough, if you press F1 while displaying the dialog defined in Listing 3.10, the Help command is automatically launched, as if you clicked the Help Button! That's because commands such as Help define a default input gesture that executes the command. You can bind your own input gestures to a command by adding KeyBinding and/or MouseBinding objects to the relevant element's InputBindings collection. For example, to assign F2 as a keyboard shortcut that executes Help, you could add the following statement to AboutDialog's constructor:
this.InputBindings.Add( new KeyBinding(ApplicationCommands.Help, new KeyGesture(Key.F2)));
This would make both F1 and F2 execute Help, however. You could additionally suppress the default F1 behavior by binding F1 to a special NotACommand command as follows:
this.InputBindings.Add( new KeyBinding(ApplicationCommands.NotACommand, new KeyGesture(Key.F1)));
Both of these statements could alternatively be represented in XAML as follows:
<Window.InputBindings> <KeyBinding Command="Help" Key="F2"/> <KeyBinding Command="NotACommand" Key="F1"/> </Window.InputBindings>
|

