ExceptionValidationPlugin.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Reflection;
  5. namespace Avalonia.Data.Core.Plugins
  6. {
  7. /// <summary>
  8. /// Validates properties that report errors by throwing exceptions.
  9. /// </summary>
  10. public class ExceptionValidationPlugin : IDataValidationPlugin
  11. {
  12. /// <inheritdoc/>
  13. public bool Match(WeakReference reference, string memberName) => true;
  14. /// <inheritdoc/>
  15. public IPropertyAccessor Start(WeakReference reference, string name, IPropertyAccessor inner)
  16. {
  17. return new Validator(reference, name, inner);
  18. }
  19. private class Validator : DataValidationBase
  20. {
  21. public Validator(WeakReference reference, string name, IPropertyAccessor inner)
  22. : base(inner)
  23. {
  24. }
  25. public override bool SetValue(object value, BindingPriority priority)
  26. {
  27. try
  28. {
  29. return base.SetValue(value, priority);
  30. }
  31. catch (TargetInvocationException ex)
  32. {
  33. PublishValue(new BindingNotification(ex.InnerException, BindingErrorType.DataValidationError));
  34. }
  35. catch (Exception ex)
  36. {
  37. PublishValue(new BindingNotification(ex, BindingErrorType.DataValidationError));
  38. }
  39. return false;
  40. }
  41. }
  42. }
  43. }