我有一个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"))
);
}
}
但是当我运行项目时,我一直得到一个空引用异常。我错过了什么?感谢
答案 0 :(得分:1)
在xaml使用的构造函数(构造函数2)中初始化_dataService对象解决了问题
承包商一: public MainWindowModel(DataService dataService)
{
_dataService = dataService;
}
承包商二:
public MainWindowModel()
{
_dataService = new DataService()
}