code_junkie

Using WPF Validation rules and disabling a 'Save' button

Nov 11th, 2011
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. <TextBox...
  2.  
  3. <TextBox.Text>
  4. <Binding Path ="LastName" UpdateSourceTrigger="PropertyChanged">
  5.  
  6. <Binding.ValidationRules>
  7. <local:StringRequiredValidationRule />
  8. </Binding.ValidationRules>
  9. </Binding>
  10. </TextBox.Text>
  11.  
  12. this.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(OnErrorEvent));
  13.  
  14. private int errorCount;
  15. private void OnErrorEvent(object sender, RoutedEventArgs e)
  16. {
  17. var validationEventArgs = e as ValidationErrorEventArgs;
  18. if (validationEventArgs == null)
  19. throw new Exception("Unexpected event args");
  20. switch(validationEventArgs.Action)
  21. {
  22. case ValidationErrorEventAction.Added:
  23. {
  24. errorCount++; break;
  25. }
  26. case ValidationErrorEventAction.Removed:
  27. {
  28. errorCount--; break;
  29. }
  30. default:
  31. {
  32. throw new Exception("Unknown action");
  33. }
  34. }
  35. Save.IsEnabled = errorCount == 0;
  36. }
  37.  
  38. int count = 0;
  39.  
  40. private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
  41. {
  42. if (e.Action == ValidationErrorEventAction.Added)
  43. {
  44. button1.IsEnabled = false;
  45. count++;
  46. }
  47. if (e.Action == ValidationErrorEventAction.Removed)
  48. {
  49. count--;
  50. if (count == 0) button1.IsEnabled = true;
  51. }
  52. }
Add Comment
Please, Sign In to add comment