LogicalNotNode.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.Globalization;
  5. using Avalonia.Data;
  6. namespace Avalonia.Data.Core
  7. {
  8. public class LogicalNotNode : ExpressionNode, ITransformNode
  9. {
  10. public override string Description => "!";
  11. protected override void NextValueChanged(object value)
  12. {
  13. base.NextValueChanged(Negate(value));
  14. }
  15. private static object Negate(object v)
  16. {
  17. if (v != AvaloniaProperty.UnsetValue)
  18. {
  19. var s = v as string;
  20. if (s != null)
  21. {
  22. bool result;
  23. if (bool.TryParse(s, out result))
  24. {
  25. return !result;
  26. }
  27. else
  28. {
  29. return new BindingNotification(
  30. new InvalidCastException($"Unable to convert '{s}' to bool."),
  31. BindingErrorType.Error);
  32. }
  33. }
  34. else
  35. {
  36. try
  37. {
  38. var boolean = Convert.ToBoolean(v, CultureInfo.InvariantCulture);
  39. return !boolean;
  40. }
  41. catch (InvalidCastException)
  42. {
  43. // The error message here is "Unable to cast object of type 'System.Object'
  44. // to type 'System.IConvertible'" which is kinda useless so provide our own.
  45. return new BindingNotification(
  46. new InvalidCastException($"Unable to convert '{v}' to bool."),
  47. BindingErrorType.Error);
  48. }
  49. catch (Exception e)
  50. {
  51. return new BindingNotification(e, BindingErrorType.Error);
  52. }
  53. }
  54. }
  55. return AvaloniaProperty.UnsetValue;
  56. }
  57. public object Transform(object value)
  58. {
  59. var originalType = value.GetType();
  60. var negated = Negate(value);
  61. if (negated is BindingNotification)
  62. {
  63. return negated;
  64. }
  65. return Convert.ChangeType(negated, originalType);
  66. }
  67. }
  68. }