zoukankan      html  css  js  c++  java
  • (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.自定义命令 

     

  • 相关阅读:
    linux查看端口被占用等常用命令
    python批量修改文件内容及文件编码方式的处理
    为什么在Python里推荐使用多进程而不是多线程
    python小练习之读取文件写入excel
    python 小练习之生成手机号码
    python 小练习之删除文件夹下的所有文件,包括子文件夹中的文件
    python中 字符 字典 列表之间的转换
    统计表中 重复出现 XX次以上的数据
    java数据类型
    字符编码和python使用encode,decode转换utf-8, gbk, gb2312
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/12171454.html
Copyright © 2011-2022 走看看