Tuesday, June 26, 2007

WPF Commands

Irena Kennedy has a WPF ApplicationCommands sample on her blog. The sample is very simple but shows how to hook cut/copy/paste/undo/redo commands for a textbox in WPF. However, there are some minor issues. The sample explicitly sets the command target which prevents each of the commands from targeting the control that has focus. A better approach is to add each of the commands to a toolbar or menu:

<Menu>
    <MenuItem Header="Edit">
        <MenuItem Command="ApplicationCommands.Cut" />
        <MenuItem Command="ApplicationCommands.Copy" />
        <MenuItem Command="ApplicationCommands.Paste" />
        <MenuItem Command="ApplicationCommands.Undo" />
        <MenuItem Command="ApplicationCommands.Redo" />
    </MenuItem>
</Menu>

Menus have native support for ICommand.CanExecuteChanged so the MenuItems correctly reflect ICommand.CanExecute using Control.Enabled.

Have a look at the Commanding Overview in the MSDN for more detailed information.

Technorati Tags: , ,

1 comment:

  1. As an aside, it's interesting to see that WPF supports cut/copy/paste/undo/redo out of the box.

    ReplyDelete