Updated on Kisan Patel
Commands are an input mechanism in WPF application that provides a way for handling input data. The simplest way to use a command in WPF is to use the predefined RoutedCommand class from one of the command library classes. Some of the common examples of predefined commands are Cut, Copy and Paste in the ApplicationCommand
class.
A command source triggers a command. For example, a Button or a MenuItem control can be a command source. Command sources in WPF implement the ICommandSource interface.
Properties of the ICommandSource
Interface
Command – Executes when a command source is invoked.
CommandTarget – Retrieves the Command object on which the command is executed.
CommandParameter – Passes information to the handlers implementing a command.
The MenuItem
control has native support for invoking commands.
MainWindow.xaml
<Window x:Class="WPFStackPanelDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Menu> <MenuItem Command="ApplicationCommands.Copy" /> <MenuItem Command="ApplicationCommands.Cut" /> <MenuItem Command="ApplicationCommands.Paste" /> </Menu> <TextBox Name="TextBox1" Width="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10, 40, 0, 0"/> <TextBox Name="TextBox2" Width="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10, 80, 0, 0"/> </Grid> </Window>
In above code, you can see three MeuItems controls with the Cut, Copy and Paste commands. When you run the application and perform action on the TextBox
, you will get the below output: