ArrayElementPlugin.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using Avalonia.Data;
  4. using Avalonia.Data.Core.Plugins;
  5. namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
  6. {
  7. internal class ArrayElementPlugin : IPropertyAccessorPlugin
  8. {
  9. private readonly int[] _indices;
  10. private readonly Type _elementType;
  11. public ArrayElementPlugin(int[] indices, Type elementType)
  12. {
  13. _indices = indices;
  14. _elementType = elementType;
  15. }
  16. [RequiresUnreferencedCode(TrimmingMessages.PropertyAccessorsRequiresUnreferencedCodeMessage)]
  17. public bool Match(object obj, string propertyName)
  18. {
  19. throw new InvalidOperationException("The ArrayElementPlugin does not support dynamic matching");
  20. }
  21. [RequiresUnreferencedCode(TrimmingMessages.PropertyAccessorsRequiresUnreferencedCodeMessage)]
  22. public IPropertyAccessor? Start(WeakReference<object?> reference, string propertyName)
  23. {
  24. if (reference.TryGetTarget(out var target) && target is Array arr)
  25. {
  26. return new Accessor(new WeakReference<Array>(arr), _indices, _elementType);
  27. }
  28. return null;
  29. }
  30. class Accessor : PropertyAccessorBase
  31. {
  32. private readonly int[] _indices;
  33. private readonly WeakReference<Array> _reference;
  34. public Accessor(WeakReference<Array> reference, int[] indices, Type elementType)
  35. {
  36. _reference = reference;
  37. _indices = indices;
  38. PropertyType = elementType;
  39. }
  40. public override Type PropertyType { get; }
  41. public override object? Value => _reference.TryGetTarget(out var arr) ? arr.GetValue(_indices) : null;
  42. public override bool SetValue(object? value, BindingPriority priority)
  43. {
  44. if (_reference.TryGetTarget(out var arr))
  45. {
  46. arr.SetValue(value, _indices);
  47. return true;
  48. }
  49. return false;
  50. }
  51. protected override void SubscribeCore()
  52. {
  53. PublishValue(Value);
  54. }
  55. protected override void UnsubscribeCore()
  56. {
  57. }
  58. }
  59. }
  60. }