简体   繁体   English

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

[英]RelayCommand implementation : Object reference not set to an instance of an object

I have a WPF Project and I am using a RelayCommand for button click event. 我有一个WPF项目,并且正在使用RelayCommand进行按钮单击事件。 Here is the constractor of my MainViewModel 这是我的MainViewModel的承包商

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

// RelayCommandClass // 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
}

//Region for Command Implementation //命令执行区域

    private RelayCommand _validateResponse;

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


        }

    }

But When I run the project I keep getting a null reference exception. 但是,当我运行该项目时,我总是收到空引用异常。 Did I miss something? 我错过了什么? Thanks 谢谢

Initializing the _dataService object at the constructor(constructor two) used by xaml solved the problem 在xaml使用的构造函数(构造函数2)处初始化_dataService对象解决了该问题

contractor one: 承包商一:

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

contractor two: 承包商二:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM