(19)WPF 命令

命令将控件连接到命令,不需要重复编写事件处理代码,当命令不能可用时,自动禁用控件来管理用户界面的状态

命令将事件委托到适当的命令

控件的启用太壮和相应的命令状态保持同步

一、命令模型

1.ICommand

命令的核心是ICommand接口

public interface ICommand
{
  //返回一个状态是否可用的bool值
    bool CanExecute(object parameter); 
  
//包含任务程序的逻辑 void Execute(object parameter);
  
//命令状态改变时发生的事件 event EventHandler CanExecuteChanged; }

2.RoutedCommand类

RoutedCommand类继承了ICommand接口,所有的命令都继承自该类或他的子类

 

3.RoutedUICommand

RoutedUICommand类继承RoutedCommand,所有预先构建好的命令都继承自此类

 

4.命令库

WPF的基本命令由五个专门的静态类提供

(1)ApplicationCommands

提供了复制、粘贴、保存、打印等命令。

{Cut,Copy,Paste,Undo,Redo,Delete,Find,Replace,Help,SelectAll,New,Open,Save,SaveAs,Print,CancelPrint,PrintPreview,Close,Properties,ContextMenu,CorrectionList,Stop,NotACommand,Last}

(2)NavigationCommands

提供导航命令

(3)EditingCommands

文档编辑命令

(4)ComponentCommands
用户界面组件使用的命令

(5)MediaCommands

多媒体命令

 

二、命令使用

1.命令源 

触发命令的最简单方式是使用实现了ICommandSource接口的控件

ICommandSource有三个属性

  • Command:指向连接命令(必须)
  • CommandParamter:提供希望随命令发送的数据(非必须)
  • CommandTarget:确定将在其中执行命令元素(非必须)

 

        <Button Command="ApplicationCommands.New" x:Name="btn1" Width="200" Height="50" >new1</Button>
        <!--简写-->
        <Button Command="New" x:Name="btn2" Width="200" Height="50" >new2</Button>

 2.命令绑定

代码方式

        public MainWindow()
        {
            InitializeComponent();
            CommandBinding commandBinding = new CommandBinding(ApplicationCommands.New);
            commandBinding.Executed += NewCommand_Executed;
            this.CommandBindings.Add(commandBinding);
        }

        private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("NewCommand_Executed方法");
        }

xaml方式

    <Window.CommandBindings>
        <CommandBinding Command="New" Executed="NewCommand_Executed" />
    </Window.CommandBindings>

    <StackPanel>
        <Button Command="New" x:Name="btn2" Width="200" Height="50" >new2</Button>
    </StackPanel>

 

 3.禁用命令

commandBinding.CanExecute += NewCommand_CanExecute;

      private void NewCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = b;
        }

 

 

 

 

三、高级命令

1.自定义命令 

 

 

 

 

posted @ 2020-01-09 14:44  富坚老贼  阅读(240)  评论(0)    收藏  举报