ソースコード
App.xaml
<Application x:Class="WpfApplication7.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> </Application>
MainWindow.xaml
<Window x:Class="WpfApplication7.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:WpfApplication7" Title="MainWindow" Height="350" Width="525"> <DockPanel LastChildFill="False"> <Menu DockPanel.Dock="Top"> <MenuItem Header="ファイル(_F)"> <MenuItem Header="保存(_S)"> <MenuItem.Command> <l:SaveCommand /> </MenuItem.Command> </MenuItem> </MenuItem> </Menu> </DockPanel> </Window>
MainWindow.xaml.cs
using System.Windows; namespace WpfApplication7 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); RoutedEventHandler handler = (s, e) => MessageBox.Show("保存されました。"); this.AddHandler(SaveCommand.SaveEvent, handler); } } }
SaveCommand.cs
using System; using System.Windows; using System.Windows.Input; namespace WpfApplication7 { class SaveCommand : ICommand { public bool CanExecute(object parameter) { return true; } // バブルアップするイベントを定義 public static readonly RoutedEvent SaveEvent = EventManager.RegisterRoutedEvent( "Save", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SaveCommand)); public event EventHandler CanExecuteChanged; public void Execute(object parameter) { // 現在の要素を検索し、適切なイベントを発生させる。 RoutedEventArgs e = new RoutedEventArgs(SaveCommand.SaveEvent, Keyboard.FocusedElement); Keyboard.FocusedElement.RaiseEvent(e); } } }