Built-in Commands




WPF Tutorial Contents

APL  Home Page


Built-in Commands

Here's some XAML from the Nathan book...

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <StackPanel Orientation="Horizontal" Height="25">
    <Button Command="Cut" CommandTarget="{Binding ElementName=textBox}"
            Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
     <Button Command="Copy" CommandTarget="{Binding ElementName=textBox}"
            Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
     <Button Command="Paste" CommandTarget="{Binding ElementName=textBox}"
            Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
     <Button Command="Undo" CommandTarget="{Binding ElementName=textBox}"
            Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
      <Button Command="Redo" CommandTarget="{Binding ElementName=textBox}"
            Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" />
      <TextBox x:Name="textBox" Width="200" />
    </StackPanel>
</Window>


Load-and-show with Dyalog and bingo, you get Cut/Copy/Paste/Undo/Redo all without writing any code of your own.  My guess (not done this yet) is that instead of buttons you could use menu items (if you're using the classic menu/toolbar windows design).

Notice also that some WPF controls have their own command bindings.  Nathan mentions TextBox and I confirm that the keyboard shortcut Ctrl-V "just works" - there's no need for any code or anything in the XAML.  Whichever other controls have this functionality is (following Nathan) something for the reader to discover.

Having slavishly copied the above, there's a snag if you define a custom Button with both an Image and a Label - attempts to define Content in XAML result in an error to the effect that Content cannot be defined twice.  Fortunately, things seem to continue to "just work" if you don't bother to include the Content, thus...

[...]
<Button Margin="0,5,0,5" MinWidth="100" Command="Copy" CommandTarget="{Binding ElementName=txtBody}">
<StackPanel Orientation="Horizontal">
 <Image Source="%homefolder%/Images/copy.png"/>
 <Label Content="Copy"/>
 </StackPanel>
 </Button>
[...]
 <TextBox HorizontalAlignment="Left" Margin="0" Name="txtBody" VerticalAlignment="Top" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" MaxHeight="500" MaxWidth="800"/>
 </StackPanel>
[...]


Which defines a Button (with Image and Label) that copies selected text to the Clipboard.