RelayCommand实现:对象引用不设置为对象的实例

本文关键字:对象 实例 设置 实现 对象引用 RelayCommand | 更新日期: 2023-09-27 18:03:55

我有一个WPF项目,我使用RelayCommand按钮点击事件。这是我的MainViewModel的构造函数

    private readonly DataService _dataService;
      public MainWindowModel(DataService dataService)
    {
        _dataService = dataService;
    }
//RelayCommandClass

    public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    private Action<object> action;
    #endregion // Fields
    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }
    //public RelayCommand(Action<object> action)
    //{
    //    this.action = action;
    //}
    #endregion // Constructors
    #region ICommand Members
    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public void Execute(object parameter)
    {
        _execute(parameter);
    }
    #endregion // ICommand Members
}

//命令执行区域

    private RelayCommand _validateResponse;
    public RelayCommand ValidateResponse
    {
        get
        {
            return _validateResponse ?? (_validateResponse = new RelayCommand(
                                                                 parm => _dataService.Validate("string1","string2"))
                     );

        }
    }

但是当我运行项目时,我一直得到一个空引用异常。我错过什么了吗?由于

RelayCommand实现:对象引用不设置为对象的实例

在xaml使用的构造函数(构造函数2)初始化_dataService对象解决了这个问题

承包商:

  public MainWindowModel(DataService dataService)
    {
        _dataService = dataService;
    }

承包商二:

 public MainWindowModel()
    {
         _dataService = new DataService()
    }