- WPF 教程
- WPF - 主页
- WPF - 概览
- WPF - 环境设置
- WPF - Hello World
- WPF - XAML 概述
- WPF - 元素树
- WPF - 依赖属性
- WPF - 路由事件
- WPF - 控件
- WPF - 布局
- WPF - 布局的嵌套
- WPF - 输入
- WPF - 命令行
- WPF - 数据绑定
- WPF - 资源
- WPF - 模板
- WPF - 样式
- WPF - 触发器
- WPF - 调试
- WPF - 自定义控件
- WPF - 异常处理
- WPF - 本地化
- WPF - 交互
- WPF - 二维图形
- WPF - 三维图形
- WPF - 多媒体
- WPF 有用资源
- WPF - 快速指南
- WPF - 有用资源
- WPF - 讨论
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; } } }
编译并执行以上代码后,将生成以下窗口 −
现在,你可以从菜单或快捷键命令访问这些菜单项。从任一选项中,它将执行命令。
wpf_input.htm
广告