谈谈MVVM中DelegateCommand:ICommand的原理

来源:互联网 发布:友鼓谱软件免费下载 编辑:程序博客网 时间:2024/05/23 01:26

 在学习MVVM的过程中,用到了ICommand这个重要的消息模式,不过都是看的前辈们的代码去模仿。

  我想,学习不仅要学技能,更要学原理。

  当我们谈及Commands时,一般说来,Command有两个功能:

  a:执行一个特殊的行为:command的主要功能。

  b:确定某一UIElement的视觉状态(visual state):例如确定button是否可用。

  DelegateCommand - ICommand可复用实现类

  DelegateCommand:实现了ICommand,当需要使用command时,可用使用此类。(多在viewmodel中)

  ICommand组成如下:

  DelegateCommand:ICommand复用消息类

  DelegateCommand:实现了ICommand,当需要使用ICommand时,可用使用此类。(多在viewmodel中)

  ICommand组成如下:

namespace System.Winndows.Input

{

       public interface ICommand

      {

               event EventHandler CanExecuteChanged;

               bool CanExecute(object parameter);

              void Execute(object parameter);

      }

}


  

 

  ICommand成员如下:

  a:CanExecuteChanged事件和CanExecute方法被用来确定command所施加控件的视觉状态,它们是这样工作的:当某command施加于某控件时,控件会调用CanExecute方法,来确定初始的视觉状态,假设调用者是button,如果CanExecute方法返回false,button会被禁用。button同时也会订阅CanExecuteChanged事件。当触发CanExecuteChanged事件时,会再次调用CanExecute以确定是否需要修改视觉状态。

  b:Execute方法比较直白:当需要执行某些行为操作时,控件会调用它。例如,当按下按钮时。

  本篇文章只是谈对ICommand的原理的理解。

0 0