Rants and Raves

Thanks for visiting my blog!

WPF Commands are COOL!
WPF Commands are COOL!
December 26, 2024
WPF

I’ve been digging into the Command infrastructure in WPF lately and I really like the way it works.  Essentially it is a way to separate the idea that you have commands that a particular applciation can execute and the ways you start a command (e.g. menu, toolbar button, context menu, hotkey, pen gesture). WPF comes a standard set of commands that are commonly used (e.g. New, Close, Copy, Paste, Cut, etc.).  You can define your own commands fairly easily as well.

In the XAML you can declaratively specify the commands like so:

  <Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.New"
                    Executed="OnNew"  />
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="OnClose"
                    CanExecute="OnCanClose"/>
    <CommandBinding Command="local:Window1.ImportFileCommand"
                    Executed="OnImportFile" />
    <CommandBinding Command="local:Window1.ExportFileCommand"
                    Executed="OnExportFile" />
    <CommandBinding Command="local:Window1.ChangeViewCommand"
                    Executed="OnChangeView" />
  </Window.CommandBindings>`

Finally, you can specify the command on XAML elements (with an optional CommandParameter) like so:

    <Menu DockPanel.Dock="Top">
      <MenuItem Header="File">
        <MenuItem Header="New" Command="ApplicationCommands.New" />
        <Separator/>
        ...
    </Menu>
    <ToolBar DockPanel.Dock="Top">
      <Button Command="ApplicationCommands.New">New File</Button>
      ...
    </ToolBar>

Then you can create a single event to handle whichever way the commands are executed (see the Executed attribute on the CommandBinding above).

Lastly, I really like the CanExecute facility which allows you to have a callback that can determine whether a particular command is enabled or not.  This callback is executed by WPF to see whether to disable any controls that are tied to that command.  If one is disabled (like in a Menu and in a toolbar) they both get disabled.

I hope to have a good example to share with you in the next couple of days.