Wpf-routed-commands

提供:Dev Guides
移動先:案内検索

WPF-RoutedCommands

RoutedCommandsは、よりセマンティックレベルでの入力処理を可能にします。 これらは実際には、新規、開く、コピー、切り取り、保存などの簡単な手順です。 これらのコマンドは非常に便利で、メニューまたはキーボードショートカットからアクセスできます。 コマンドが使用できなくなると、コントロールが無効になります。 次の例では、メニュー項目のコマンドを定義しています。

  • WPFCommandsInput という名前の新しいWPFプロジェクトを作成しましょう。
  • メニューコントロールをスタックパネルにドラッグし、次のXAMLファイルに示すように、次のプロパティとコマンドを設定します。
<Window x:Class = "WPFContextMenu.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:WPFContextMenu"
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525">

   <Grid>
      <StackPanel x:Name = "stack" Background = "Transparent">

         <StackPanel.ContextMenu>
            <ContextMenu>
               <MenuItem Header = "New" Command = "New"/>
               <MenuItem Header = "Open" Command = "Open"/>
               <MenuItem Header = "Save" Command = "Save"/>
            </ContextMenu>
         </StackPanel.ContextMenu>

         <Menu>
            <MenuItem Header = "File" >
               <MenuItem Header = "New" Command = "New"/>
               <MenuItem Header = "Open" Command = "Open"/>
               <MenuItem Header = "Save" Command = "Save"/>
            </MenuItem>
         </Menu>

      </StackPanel>
   </Grid>

</Window>

さまざまなコマンドが処理されるC#コードを次に示します。

using System.Windows;
using System.Windows.Input;

namespace WPFContextMenu {
  ///<summary>
     ///Interaction logic for MainWindow.xaml
  ///</summary&gt

   public partial class MainWindow : Window {

      public MainWindow() {
         InitializeComponent();
         CommandBindings.Add(new CommandBinding(ApplicationCommands.New, NewExecuted, CanNew));
         CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, OpenExecuted, CanOpen));
         CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, SaveExecuted, CanSave));
      }

      private void NewExecuted(object sender, ExecutedRoutedEventArgs e) {
         MessageBox.Show("You want to create new file.");
      }

      private void CanNew(object sender, CanExecuteRoutedEventArgs e) {
         e.CanExecute = true;
      }

      private void OpenExecuted(object sender, ExecutedRoutedEventArgs e) {
         MessageBox.Show("You want to open existing file.");
      }

      private void CanOpen(object sender, CanExecuteRoutedEventArgs e) {
         e.CanExecute = true;
      }

      private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) {
         MessageBox.Show("You want to save a file.");
      }
      private void CanSave(object sender, CanExecuteRoutedEventArgs e) {
         e.CanExecute = true;
      }
   }

}

上記のコードをコンパイルして実行すると、次のウィンドウが生成されます-

ルーティングされたコマンドの出力

これで、メニューまたはショートカットキーコマンドからこのメニュー項目にアクセスできます。 どちらのオプションからも、コマンドを実行します。