WPF Commanding

WPF Commanding is a new way to wire-up UI events. This post will demonstrate how this works by using a TextBox and a standard Edit menu.

Let’s start with a skeleton application:

<Grid x:Name="grid1">
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition Height="22" />
    <RowDefinition />
  </Grid.RowDefinitions>
  <Menu Grid.Column="0" Grid.Row="0" VerticalAlignment="Top">
    <MenuItem Header="_Edit">
      <!-- Menu items will go here-->
    </MenuItem>
  </Menu>
  <TextBox x:Name="txtDocument" Grid.Column="0" Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" AcceptsReturn="True" AcceptsTab="True" Margin="0,-0.723,0,0.723" />
</Grid>

Here’s the magic, the menu items only require a single attribute called Command. Their text, shortcut keys and function are ALL determined by this attribute. The commands below are all handled, automatically by the TextBox:

<MenuItem Command="Undo" />
<MenuItem Command="Redo" />
<Separator/>
<MenuItem Command="Cut" />
<MenuItem Command="Copy" />
<MenuItem Command="Paste" />
<Separator/>
<MenuItem Command="SelectAll" />

That’s all you need. No coding required! Richard Griffin has an excellent blog post on the subject here.

Further information can be found on MSDN:
Commanding Overview

Advertisements
This entry was posted in Tips and Tricks and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s