First, add the application namespace at the top of xaml file that will use the binding: ex.
xmlns:main="clr-namespace:MyApplication"
Next, add a custom static class to contain the commands, outside the main window class: ex.
public static class Command
{
public static RoutedCommand GSToggleCmd = new RoutedCommand();
public static RoutedCommand ScreenZoomCmd = new RoutedCommand();
}
My main window class happened to be 'MainWindow'; I defined the Command class right below it.
Finally, add the command bindings in the xaml file
<Window.CommandBindings>
<CommandBinding Command="main:Command.GSToggleCmd" Executed="GameStateToggleExecuted" />
<CommandBinding Command="main:Command.ScreenZoomCmd" Executed="ApplyScreenFitCmd" />
</Window.CommandBindings>
Command=""
refers to the RoutedCommand
that you'll be binding to. I've named my namespace reference main
, hence the syntax main:Command.nameofcommand
Executed=""
refers to the function called when the command is triggered.
Example of Executed
function:
private void ApplyScreenFitCmd( object sender, ExecutedRoutedEventArgs args )
{
string proportionStr = args.Parameter as string;
}
And that's it. A minimalistic, simple approach to using CommandBindings
in WPF
.
To add a command, just chuck in a new static RoutedCommand
in the Command
class and add the CommandBinding
in the xaml file under Window.CommandBindings
Note:
Visual Studio's Xaml editor may complain at first that some command cannot be found. Building the project will resolve the issue.
Further Information:
You can also trigger CommandBindings
through InputBindings. (key triggers)
Example (placed in the Xaml file that will use them):
<Window.InputBindings>
<KeyBinding Key="F5" Command="main:Command.GSToggleCmd" />
<KeyBinding Modifiers="Shift+Alt" Key="Q" Command="main:Command.ScreenZoomCmd" CommandParameter="1.0" />
<KeyBinding Modifiers="Alt" Key="W" Command="main:Command.ScreenZoomCmd" CommandParameter="0.75" />
<KeyBinding Modifiers="Alt" Key="E" Command="main:Command.ScreenZoomCmd" CommandParameter="0.5" />
</Window.InputBindings>
So it's basically the Key
press triggers KeyBinding
, which in turn triggers the CommandBinding
of the command specified, triggering the corresponding call function.
As with the above example, you can also define CommandParameter
to send in a parameter to the function finally called. The nice thing about this is that, like the above, you can reuse the same CommandBinding
by just chucking in different CommandParameters
.
You can also trigger CommandBindings
through Buttons, MenuItems, etc.
Example:
<MenuItem Header="100%" InputGestureText="Alt+Q" Command="main:Command.ScreenZoomCmd" CommandParameter="1.0"/>
This is the same syntax as with the InputBindings
.
It took me a while before I settled down on a minimalistic, uniform way to use bindings in WPF. I hope this article prevents all the struggle that this concept seems to easily cause.