第七章-命令

一、命令的概念

WPF命令是一种任务封装、用于实现MVVM模式中的重要一环。

命令系统包括命令、命令源、命令目标和命令绑定,它们共同构成了WPF中的主要核心要素。

命令与模板、数据绑定一起,实现了前后端的逻辑分离

 

二、命令的组成

(1)命令(继承ICommand接口)
RoutedUICommand->RoutedCommand->ICommand

命令库(预定义):5个静态类(5组)。大部分都是RoutedUICommand对象。
ApplicationCommands、NavigationCommands、EditingCommands、ComponentCommands、MediaCommands

(2)命令源(ICommandSource)
调用命令的对象
  (2.1)Command:指向连接的命令。必须有
  (2.2)CommandParameter:提供其他希望随命令发送的数据,
  (2.3)CommandTarget:确定将在执行命令的元素。
(3)命令目标:是要在其上执行命令的对象。继承IInputElement即可
(4)命令绑定(CommandBinds)将某个命令与一些逻辑代码进行绑定

  <!--命令对象为ApplicationCommands.New
      执行逻辑为CommandBinding_Executed
      二者通过以下代码绑定
  -->
  <Window.CommandBindings>
      <CommandBinding Command="ApplicationCommands.New" Executed="CommandBinding_Executed"></CommandBinding>
      
  </Window.CommandBindings>
  <StackPanel>
      <Button Command="ApplicationCommands.New"  CommandTarget="{Binding ElementName=btn_Target}">按钮(命令源)</Button>

      <Button x:Name="btn_Target">命令目标</Button>
  </StackPanel>

 

三、自定义命令

 public class CustCmd : ICommand
 {
     public event EventHandler? CanExecuteChanged;//命令状态发生改变的事件

     // 能否执行该命令,命令状态
     public bool CanExecute(object? parameter)
     {
         return true;
     }

     // 如何执行,目前未分离业务
 

     public void Execute(object? parameter)
     {
         //业务逻辑
         MessageBox.Show($"已经在执行,参数为{parameter}");
     }
 }
  <Window.Resources>
      <cmd:CustCmd x:Key="cuscmd"></cmd:CustCmd>
  </Window.Resources>
  <Grid>
      <Button Command="{StaticResource cuscmd}" CommandParameter="Hello" Width="400" Height="200"> 自定义命令</Button>
  </Grid>

 

 

四、将业务代码修改为委托类型

  当没有参数、没有返回值:使用Action

  当有参数、没有返回值:使用Action<T1,T2...>

  当没有参数,有返回值使用Func<T1>

  当有参数、有返回值:使用Func<T1,T2>

 //将业务从命令地址分离出来,将要处理的业务方法传递给命令(系统委托)
 public class CustCmdNotBusin : ICommand
 {
     //1、无参数、无返回值
     public Action CmdAction { set; get; }   //委托
     public event EventHandler? CanExecuteChanged;

     public bool CanExecute(object? parameter)
     {
         return true;
     }

     public void Execute(object? parameter)
     {
         if (CmdAction != null)
         {
             CmdAction.Invoke();//执行委托
         }
     }
 }

  

posted @ 2025-12-15 23:03  nonAny  阅读(3)  评论(0)    收藏  举报