简体   繁体   中英

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. Here is the constractor of my 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
}

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

contractor one:

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

contractor two:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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