This article is currently in the process of being translated into Polish (~23% done).


Implementing a custom WPF Command

W poprzednim rozdziale przyjrzeliśmy się różnym sposobom używania poleceń zwanych po angielsku "commands", które są standardowo zdefiniowane w WPF. Możesz jednak zaimplementować swoje własne polenecia. Jest to dość proste i kiedy stworzysz własne polecenia, możesz ich używać tak samo jak tych standardowych w WPF.

Najłatwiejszym sposobem używania własnych poleceń jest stworzenie statycznej klasy static class która je zawiera. W takiej klasie każda komenda jest utwożona jako statyczne pole możliwe do wykorzystnia w aplikacji. Jako, że WPF nie zawiera zdefiniowanych komand Exit/Quit, postanowiłem dla przykładu właśnie je zaimplementować. Wygląda to następująco:

<Window x:Class="WpfTutorialSamples.Commands.CustomCommandSample"
        Title="CustomCommandSample" Height="150" Width="200">
        <CommandBinding Command="self:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <MenuItem Header="File">
                <MenuItem Command="self:CustomCommands.Exit" />
        <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Command="self:CustomCommands.Exit">Exit</Button>
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;

namespace WpfTutorialSamples.Commands
	public partial class CustomCommandSample : Window
		public CustomCommandSample()

		private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
			e.CanExecute = true;

		private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)

	public static class CustomCommands
		public static readonly RoutedUICommand Exit = new RoutedUICommand
				new InputGestureCollection()
					new KeyGesture(Key.F4, ModifierKeys.Alt)

		//Define more commands here, just like the one above

In the markup, I've defined a very simple interface with a menu and a button, both of them using our new, custom Exit command. This command is defined in Code-behind, in our own CustomCommands class, and then referenced in the CommandBindings collection of the window, where we assign the events that it should use to execute/check if it's allowed to execute.

All of this is just like the examples in the previous chapter, except for the fact that we're referencing the command from our own code (using the "self" namespace defined in the top) instead of a built-in command.

In Code-behind, we respond to the two events for our command: One event just allows the command to execute all the time, since that's usually true for an exit/quit command, and the other one calls the Shutdown method that will terminate our application. All very simple.

As already explained, we implement our Exit command as a field on a static CustomCommands class. There are several ways of defining and assigning properties on the commands, but I've chosen the more compact approach (it would be even more compact if placed on the same line, but I've added line breaks here for readability) where I assign all of it through the constructor. The parameters are the text/label of the command, the name of the command, the owner type and then an InputGestureCollection, allowing me to define a default shortcut for the command (Alt+F4).


Implementing custom WPF commands is almost as easy as consuming the built-in commands, and it allows you to use commands for every purpose in your application. This makes it very easy to re-use actions in several places, as shown in the example of this chapter.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!