Condividi tramite


How to: Add a Command to a MenuItem

The following example shows how to set up a MenuItem as the command source for the Paste command. For more information on commanding, see the Commanding Overview.

Example

MenuItem, such as Button and Hyperlink, implements ICommandSource. Two properties that ICommandSource expose are Command and CommandTarget. Command is the command that will be invoked and CommandTarget is the element where event routing will start when the command is invoked. If CommandTarget is not defined, the element that has keyboard focus will be the set as the target.

The class implementing ICommandSource defines what it means for the command to be invoked. MenuItem and Button define the Click event as the means to invoke the command. If the command cannot be executed on the particular CommandTarget, the MenuItem will be disabled. When the command can execute on the CommandTarget, the MenuItem will be enabled.

In this example, a MenuItem is created on the main Window of the application. The Command property is set to the Paste command. CommandTarget is not defined on the MenuItem; therefore, the target of the command will be the element that has keyboard focus.

Since the TextBox class supplies logic for the Paste command, a CommandBinding is not required. If the control handling the command does not supply logic for the execution of the command, a CommandBinding is required to bind the ExecutedRoutedEventHandler and CanExecuteRoutedEventHandler to the RoutedCommand.

<Window x:Class="SDKSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuItemCommandTask"
    >
    <DockPanel>
      <Menu DockPanel.Dock="Top">
        <MenuItem Command="ApplicationCommands.Paste" Width="75" />
      </Menu>
      <TextBox BorderBrush="Black" BorderThickness="2" Margin="25"
               TextWrapping="Wrap">
        The MenuItem will not be enabled until
        this TextBox gets keyboard focus  
      </TextBox>
    </DockPanel>
</Window>

See Also

Reference

ApplicationCommands

Concepts

Commanding Overview
Input Overview