WPF - 路由命令



路由命令以更语义化的级别启用输入处理。这些实际上是简单的指令,如新建、打开、复制、剪切和保存。这些命令非常有用,可以从菜单或键盘快捷键中访问它们。如果命令变为不可用,它将禁用控件。以下示例定义菜单项的命令。

  • 让我们创建一个名为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> 
	
   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; 
      } 
   } 
	
}	

编译并执行以上代码后,将生成以下窗口 −

output of the Routed Commands

现在,你可以从菜单或快捷键命令访问这些菜单项。从任一选项中,它将执行命令。

wpf_input.htm
广告