MVVM架构浅谈 – ICommand

WPF或者UWP在使用MVVM框架开发的时候,不仅要绑定数据,还需要绑定命令(用户交互的操作)。在ViewModel中我们使用INotifyPropertyChanged接口对数据进行更新,同时我们需要使用实现ICommand对命令进行触发。下面就讲讲ICommand的使用。

ICommand的结构

public interface ICommand
{
    //当出现影响是否应执行命令的更改时发生
    event EventHandler CanExecuteChanged;

    //定义用于确定此命令是否在其当前状态下执行的方法
    bool CanExecute(object parameter);

    //定义在调用此命令时调用的方法
    void Execute(object parameter);
}

一般绑定的命令集成上面的接口,然后执行 Execute方法即可。但是为了方便使用,我们可以定义一个Command公共类对ICommand继承封装。

ICommand公共类 – DelegateCommand


public class DelegateCommand : ICommand
{
    private readonly Action _executeMethod=null;
    private readonly Func<T,bool> _canExecuteMethod=null;

    public DelegateCommand(Action executeMethod)
        :this(executeMethod,null)
    {
    }

    public DelegateCommand(Action executedMethod, Func<T, bool> canExecuteMethod)
    {
        if(executeMethod==null)
            throw new ArgumentNullException("executedMethod");
        _executeMethod=executeMethod;
        _canExecuteMethod=canExecuteMethod;
    }

    public bool CanExecute(T parameter)
    {
        return _canExecuteMethod!=null ? _canExecuteMethod(parameter) : true;
    }

    public void Execute(T parameter)
    {
        _executeMethod?.Invoke(parameter);
    }

    //这个事件需要多了解
    public event EventHandler ICommand.CanExecuteChanged
    {
        add{ CommandManager.RequerySuggested += value;}
        remove{ CommandManager.RequerySuggested -= value;}
    }

    public bool CanExecute(object parameter)
    {
         if(parameter ==null && typeof(T).IsValueType)
         {
             return (_canExecuteMethod==null);
         }
         return CanExecute((T)parameter);
    }

    public void Execute(object parameter)
    {
        Execute((T)parameter);
    }
}

在View Model中Command使用如下:


private DelegateCommand _addCommand;
public ICommand AddCommand
{
    get
    {
        if(_addCommand ==null)
        {
            _addCommand =new DelegateCommand(AddCommandExecute);
        }
        return _addCommand;
    }
}

public void AddCommandExecute(object obj)
{......}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s