I have a simple wpf application and I am trying to deactivate the save button if the form has errors.
The Problem is that, although the validation it looks to works perfect, I don't know why but I am getting all the time false from the method which is responsible to check the errors.
Let me make it more clear by providing the code.
This is the code from MainWindow.Xaml.cs
private readonly HashSet<ValidationError> errors = new HashSet<ValidationError>();
private Lazy<MainWindowViewModel> viewModel;
public MainWindow() {
InitializeComponent();
InitializeValidaton();
}
void InitializeValidaton() {
viewModel = new Lazy<MainWindowViewModel>();
Validation.AddErrorHandler(this, ErrorChangedHandler);
}
private void ErrorChangedHandler(object sender, ValidationErrorEventArgs e) {
if (e.Action == ValidationErrorEventAction.Added) {
errors.Add(e.Error);
} else {
errors.Remove(e.Error);
}
//I set a breakpoint here and it returns the correct value. False if it has errors and True if not
viewModel.Value.IsValid = !errors.Any();
}
This is the command for the button
public ICommand SaveItem {
get { return new RelayCommand(SaveItemExecute,CanSaveItem); }
}
private bool CanSaveItem() {
return IsValid;
}
//I set up here a breakpoint and it returns the correct value just once.
//The application looked up on CanSaveItem all the time and except the first time, it returns wrong value
private bool _isValid;
public bool IsValid {
get { return _isValid; }
set {
_isValid = value;
RaisePropertyChanged("IsValid");
}
}
Validation Rules
[Required(ErrorMessage = "Please enter Title")]
[StringLength(100, ErrorMessage = "The maximum length is 100")]
string Name { get; set; }
I don't know if it makes any sense, but the button I want to deactivate is in a UserControl.
I can't understand why the canExecute method which is in a userControl, triggered more than once. What ever of method if I used, it has the same reaction. I mention the userControl, because if I use the same method(which in part of ICommand) in the mainWindow, it triggered just once
I will appreciate if could anyone help me with this.
Thanks