从表面看,逻辑流程是这样。但是实际上,流程很简单。
创建命令
将命令和命令源赋给指定控件
创建命令关联,将命令赋给命令关联,同时将判断 命令是否可执行 的事件,以及命令可执行时触发的事件 也赋给命令关联。(实际 这两个路由事件是命令目标发送的)
<Window x:Class="WpfDemo.RoutedCommandDemo" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="RoutedCommandDemo" Height="300" Width="300"> <StackPanel x:Name="stackPanel"> <Button Content="Button" Height="47" x:Name="btn"/> <TextBox Height="62" TextWrapping="Wrap" Text="TextBox" x:Name="txt"/> <Label Content="当输入框没有数据时,清空按钮无法被点击。" Height="59" VerticalContentAlignment="Center"/> </StackPanel> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfDemo { /// <summary> /// RoutedCommandDemo.xaml 的交互逻辑 /// </summary> public partial class RoutedCommandDemo : Window { public RoutedCommandDemo() { InitializeComponent(); InitinalizeCommand(); } private RoutedCommand ClearCommand = new RoutedCommand("Clear", typeof(RoutedCommandDemo)); public void InitinalizeCommand() { //首先创建一个命令 //其次指定命令目标 //将命令源与命令相关联, 命令可以控制 命令源是否可以使用 //创建命令关联,将命令关联与命令进行绑定, //命令源与命令目标绑定之后,后台会call 命令目标,命令目标会发出路由事件(是否可以执行,执行事件) //路由事件会被命令关联接收执行。如果不可执行,会反馈给命令。命令又会反馈命令源 // 命令关联 会告诉命令 可不可以执行,所以要关联命令。 命令会 反馈 命令源,是否可以执行 //將命令賦給命令源,并指定快捷鍵 this.btn.Command = ClearCommand; this.btn.CommandTarget = this.txt; this.ClearCommand.InputGestures.Add(new KeyGesture(Key.A,ModifierKeys.Alt)); //創建命令關聯 CommandBinding cb = new CommandBinding(); cb.Command = ClearCommand; //只關注與clearCommand相關的事件 cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecuteEvent); cb.Executed += new ExecutedRoutedEventHandler(cb_ExecuteEvent); this.stackPanel.CommandBindings.Add(cb); } public void cb_CanExecuteEvent(Object o,CanExecuteRoutedEventArgs e) { if(string.IsNullOrEmpty(this.txt.Text)) { e.CanExecute = false; }else { e.CanExecute = true; } e.Handled = true;// 禁止继续上抛 } public void cb_ExecuteEvent(Object o,ExecutedRoutedEventArgs e) { this.txt.Clear(); e.Handled = true; } } }
微软的命令库