次の方法で共有


方法 : コマンドを有効にする

更新 : 2007 年 11 月

Windows Presentation Foundation (WPF) でコマンド実行を使用する方法を次の例に示します。この例では、RoutedCommandButton に関連付け、CommandBinding を作成して、RoutedCommand を実装するイベント ハンドラを作成する方法を示しています。コマンド実行の詳細については、「コマンド実行の概要」を参照してください。

使用例

コードの最初のセクションでは、ButtonStackPanel から構成されるユーザー インターフェイス (UI) を作成し、コマンド ハンドラと RoutedCommand を関連付ける CommandBinding を作成しています。

ButtonCommand プロパティは、Close コマンドに関連付けられています。

CommandBinding は、ルート WindowCommandBindingCollection に追加されます。Executed および CanExecute イベント ハンドラは、このバインディングに結び付けられ、Close コマンドに関連付けられます。

CommandBinding を使用しない場合、コマンド ロジックは実装されず、コマンドを呼び出す機構だけが実行されます。Button がクリックされると、コマンドの対象で PreviewExecuted RoutedEvent が発生し、続いて Executed RoutedEvent が発生します。これらのイベントは、その特定のコマンドの CommandBinding を要素ツリー内で検索します。RoutedEvent は要素ツリー内をトンネリングおよびバブリングするため、CommandBinding を配置する場所には注意が必要です。CommandBinding をコマンドの対象の兄弟、または RoutedEvent のルート上にない他のノードに配置すると、CommandBinding にはアクセスできません。

<Window x:Class="WCSamples.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="CloseCommand"
    Name="RootWindow"
    >
  <Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close"
                    Executed="CloseCommandHandler"
                    CanExecute="CanExecuteHandler"
                    />
  </Window.CommandBindings>
  <StackPanel Name="MainStackPanel">
    <Button Command="ApplicationCommands.Close" 
            Content="Close File" />
  </StackPanel>
</Window>
// Create ui elements.
StackPanel CloseCmdStackPanel = new StackPanel();
Button CloseCmdButton = new Button();
CloseCmdStackPanel.Children.Add(CloseCmdButton);

// Set Button's properties.
CloseCmdButton.Content = "Close File";
CloseCmdButton.Command = ApplicationCommands.Close;

// Create the CommandBinding.
CommandBinding CloseCommandBinding = new CommandBinding(
    ApplicationCommands.Close, CloseCommandHandler, CanExecuteHandler);

// Add the CommandBinding to the root Window.
RootWindow.CommandBindings.Add(CloseCommandBinding);

コードの次のセクションでは、Executed および CanExecute イベント ハンドラを実装しています。

Executed ハンドラは、開いているファイルを閉じるメソッドを呼び出します。CanExecute ハンドラは、ファイルが開いているかどうかを判別するメソッドを呼び出します。ファイルが開いている場合、CanExecute は true に設定されます。それ以外の場合は false に設定されます。

// Executed event handler.
private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    // Calls a method to close the file and release resources.
    CloseFile();
}

// CanExecute event handler.
private void CanExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
{
    // Call a method to determine if there is a file open.
    // If there is a file open, then set CanExecute to true.
    if (IsFileOpened())
    {
        e.CanExecute = true;
    }
    // if there is not a file open, then set CanExecute to false.
    else
    {
        e.CanExecute = false;
    }
}

参照

概念

コマンド実行の概要