by Geert
20. December 2011 19:42
In Catel (2.5, not released yet, only beta available), it is possible to hook the CanExecute of a Command to the IValidationSummary automatically. This way, there is no need to check for errors manually in the CanExecute. The example below first adds a validation summary to a view model to get the validation result. Then, it uses this validation summary to automatically determine whether a command can be executed.
1. Add validation to a person view model (note how the validation adds the tag PersonValidation to a validation):
1: /// <summary>
2: /// Validates the field values of this object. Override this method to enable
3: /// validation of field values.
4: /// </summary>
5: /// <param name="validationResults">The validation results, add additional results to this list.</param>
6: protected override void ValidateFields(System.Collections.Generic.List<IFieldValidationResult> validationResults)
7: {
8: if (string.IsNullOrEmpty(FirstName))
9: {
10: validationResults.Add(FieldValidationResult.CreateError(FirstNameProperty, "First name cannot be empty", "PersonValidation"));
11: }
12:
13: if (string.IsNullOrEmpty(LastName))
14: {
15: validationResults.Add(FieldValidationResult.CreateError(LastNameProperty, "Last name cannot be empty", "PersonValidation"));
16: }
17: }
2. Add a property to the view model containing the validation summary using the ValidationToViewModel attribute.
1: [ValidationToViewModel(Tag = "PersonValidation")]
2: public IValidationSummary PersonValidationSummary { get; set; }
3. Define a command on the view model:
1: /// <summary>
2: /// Gets the Save command.
3: /// </summary>
4: public Command Save { get; private set; }
5:
6: /// <summary>
7: /// Method to invoke when the Save command is executed.
8: /// </summary>
9: private void OnSaveExecute()
10: {
11: // TODO: Handle command logic here
12: }
4. Create the command that automatically uses the validation summary using the CommandHelper class:
1: Save = CommandHelper.CreateCommand(OnSaveExecute, () => PersonValidationSummary);
With this example, the Save command on the view model can only be executed when there are no errors with the PersonValidation tag.