Execute is always called even when CanExecute is false,Is this correct?
I am using a delegate command . I have noticed that regardless CanExecute is true or false execute is always called. Is this correct? I would have assumed that Execute would have been called only if CanExecute is true.
Could you clarify?
Thanks a lot
EDITED test shows that Save is always called
[TestFixture]
public class Can_test_a_method_has_been_called_via_relay_command
{
[Test]
public void Should_be_able_to_test_that_insert_method_has_been_called_on_repository()
{
var mock = new Mock<IEmployeeRepository>();
var employeeVm = new EmployeeVM(mock.Object) {Age = 19};
employeeVm.SaveCommand.Execute(null);
mock.Verify(e=>e.Insert(It.IsAny<Employee>()));
}
[Test]
public void Should_be_able_to_test_that_insert_method_has_not_been_called_on_repository()
{
var mock = new Mock<IEmployeeRepository>();
var employeeVm = new EmployeeVM(mock.Object) { Age = 15 };
employeeVm.SaveCommand.Execute(null);
mock.Verify(e => e.Insert(It.IsAny<Employee>()),Times.Never());
}
}
public class EmployeeVM:ViewModelBase
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeVM(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
private bool _hasInserted;
public bool HasInserted
{
get { return _hasInserted; }
开发者_如何学Go set
{
_hasInserted = value;
OnPropertyChanged("HasInserted");
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged("Age");
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
private RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
return _saveCommand ?? (_saveCommand = new RelayCommand(x => Save(), x => CanSave));
}
}
private bool CanSave
{
get
{
return Age > 18;
}
}
private void Save()
{
Insert();
HasInserted = true;
}
private void Insert()
{
_employeeRepository.Insert(new Employee{Age = Age,Name = Name});
}
}
public interface IEmployeeRepository
{
void Insert(Employee employee);
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Your test methods are not testing what WPF will be doing run-time.
WPF will first determine if CanExecute evaluates to true - if it is not, the Button/MenuItem/InputBinding etc. is disabled and thus cannot be fired.
As I mentioned in my comment - this is only enforced by convention.
精彩评论