WPF Controls with Built-In Command Bindings


Some controls in WPF contain their own command bindings. Let’s look at an example. The TextBox control has its own built-in bindings for the Cut, Copy and Paste commands. This example carries forward from the previous post called WPF Commands CanExecute. What does this mean? It means that we can get cut, copy and paste functionality without and procedural code behind. It’s all done with XAML.

Here is the XAML code. We have no procedural code in this example program.

<Window x:Class="CommandsWithCommandTarget.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CommandsWithCommandTarget"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="CommandsWithCommandTarget" Height="200" Width="380">
    <DockPanel>
        <WrapPanel DockPanel.Dock="Top" Margin="3">
            <Button Command="ApplicationCommands.Cut" Width="60"
                    CommandTarget="{Binding ElementName=txtEditor}" >_Cut</Button>
            <Button Command="ApplicationCommands.Paste" Width="60" Margin="3,0"
                    CommandTarget="{Binding ElementName=txtEditor}" >_Paste</Button>
        </WrapPanel>
        <TextBox AcceptsReturn="True" AcceptsTab="True" Name="txtEditor" TextWrapping="NoWrap"/>
    </DockPanel>
</Window>

Adam Nathan in his book WPF 4.5 Unleashed by Sams on page 171 lists some of the built-in commands as shown in the list below. WPF’s built-in commands are exposed as static properties of seven different classes.

  • ApplicationCommands—Close, Copy, Cut, Delete, Find, Help, New, Open, Paste, Print, PrintPreview, Properties, Redo, Replace, Save, SaveAs, SelectAll, Stop, Undo, and more
  • ComponentCommands—MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, ScrollPageDown, ScrollPageLeft, ScrollPageRight, ScrollPageUp, SelectToEnd, SelectToHome, SelectToPageDown, SelectToPageUp, and more
  • MediaCommands—ChannelDown, ChannelUp, DecreaseVolume, FastForward, IncreaseVolume, MuteVolume, NextTrack, Pause, Play, PreviousTrack, Record, Rewind, Select, Stop, and more
  • NavigationCommands—BrowseBack, BrowseForward, BrowseHome, BrowseStop, Favorites, FirstPage, GoToPage, LastPage, NextPage, PreviousPage, Refresh, Search, Zoom, and more
  • EditingCommands—AlignCenter, AlignJustify, AlignLeft, AlignRight, CorrectSpellingError, DecreaseFontSize, DecreaseIndentation, EnterLineBreak, EnterParagraphBreak, IgnoreSpellingError, IncreaseFontSize, IncreaseIndentation, MoveDownByLine, MoveDownByPage, MoveDownByParagraph, MoveLeftByCharacter, MoveLeftByWord, MoveRightByCharacter, MoveRightByWord, and more