Browse Source

Merge pull request #2820 from MarchingCube/binding-issue

Fix issues caused by bindings system not handling weak references properly
pull/2902/head
Nikita Tsukanov 7 years ago
committed by GitHub
parent
commit
6f2b9b654e
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs
  2. 26
      src/Avalonia.Base/Data/Core/ExpressionNode.cs
  3. 8
      src/Avalonia.Base/Data/Core/ExpressionObserver.cs
  4. 11
      src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs
  5. 5
      src/Avalonia.Base/Data/Core/IndexerNodeBase.cs
  6. 4
      src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs
  7. 23
      src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs
  8. 8
      src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs
  9. 5
      src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs
  10. 3
      src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs
  11. 4
      src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs
  12. 28
      src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs
  13. 23
      src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs
  14. 21
      src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs
  15. 12
      src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs
  16. 13
      src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs
  17. 6
      src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs
  18. 18
      src/Avalonia.Base/Data/Core/SettableNode.cs
  19. 2
      src/Avalonia.Base/Data/Core/StreamNode.cs
  20. 12
      src/Avalonia.Input/Gestures.cs
  21. 2
      src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/ElementNameNode.cs
  22. 4
      src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/FindAncestorNode.cs
  23. 26
      src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs
  24. 2
      tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Property.cs
  25. 14
      tests/Avalonia.Base.UnitTests/Data/Core/Plugins/DataAnnotationsValidationPluginTests.cs
  26. 4
      tests/Avalonia.Base.UnitTests/Data/Core/Plugins/ExceptionValidationPluginTests.cs
  27. 8
      tests/Avalonia.Base.UnitTests/Data/Core/Plugins/IndeiValidationPluginTests.cs
  28. 132
      tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs

6
src/Avalonia.Base/Data/Core/AvaloniaPropertyAccessorNode.cs

@ -24,7 +24,7 @@ namespace Avalonia.Data.Core
{ {
try try
{ {
if (Target.IsAlive && Target.Target is IAvaloniaObject obj) if (Target.TryGetTarget(out object target) && target is IAvaloniaObject obj)
{ {
obj.SetValue(_property, value, priority); obj.SetValue(_property, value, priority);
return true; return true;
@ -37,9 +37,9 @@ namespace Avalonia.Data.Core
} }
} }
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
if (reference.Target is IAvaloniaObject obj) if (reference.TryGetTarget(out object target) && target is IAvaloniaObject obj)
{ {
_subscription = new AvaloniaPropertyObservable<object>(obj, _property).Subscribe(ValueChanged); _subscription = new AvaloniaPropertyObservable<object>(obj, _property).Subscribe(ValueChanged);
} }

26
src/Avalonia.Base/Data/Core/ExpressionNode.cs

@ -8,27 +8,27 @@ namespace Avalonia.Data.Core
public abstract class ExpressionNode public abstract class ExpressionNode
{ {
private static readonly object CacheInvalid = new object(); private static readonly object CacheInvalid = new object();
protected static readonly WeakReference UnsetReference = protected static readonly WeakReference<object> UnsetReference =
new WeakReference(AvaloniaProperty.UnsetValue); new WeakReference<object>(AvaloniaProperty.UnsetValue);
private WeakReference _target = UnsetReference; private WeakReference<object> _target = UnsetReference;
private Action<object> _subscriber; private Action<object> _subscriber;
private bool _listening; private bool _listening;
protected WeakReference LastValue { get; private set; } protected WeakReference<object> LastValue { get; private set; }
public abstract string Description { get; } public abstract string Description { get; }
public ExpressionNode Next { get; set; } public ExpressionNode Next { get; set; }
public WeakReference Target public WeakReference<object> Target
{ {
get { return _target; } get { return _target; }
set set
{ {
Contract.Requires<ArgumentNullException>(value != null); Contract.Requires<ArgumentNullException>(value != null);
var oldTarget = _target?.Target; _target.TryGetTarget(out var oldTarget);
var newTarget = value.Target; value.TryGetTarget(out object newTarget);
if (!ReferenceEquals(oldTarget, newTarget)) if (!ReferenceEquals(oldTarget, newTarget))
{ {
@ -72,9 +72,11 @@ namespace Avalonia.Data.Core
_subscriber = null; _subscriber = null;
} }
protected virtual void StartListeningCore(WeakReference reference) protected virtual void StartListeningCore(WeakReference<object> reference)
{ {
ValueChanged(reference.Target); reference.TryGetTarget(out object target);
ValueChanged(target);
} }
protected virtual void StopListeningCore() protected virtual void StopListeningCore()
@ -96,7 +98,7 @@ namespace Avalonia.Data.Core
if (notification == null) if (notification == null)
{ {
LastValue = new WeakReference(value); LastValue = new WeakReference<object>(value);
if (Next != null) if (Next != null)
{ {
@ -109,7 +111,7 @@ namespace Avalonia.Data.Core
} }
else else
{ {
LastValue = new WeakReference(notification.Value); LastValue = new WeakReference<object>(notification.Value);
if (Next != null) if (Next != null)
{ {
@ -125,7 +127,7 @@ namespace Avalonia.Data.Core
private void StartListening() private void StartListening()
{ {
var target = _target.Target; _target.TryGetTarget(out object target);
if (target == null) if (target == null)
{ {

8
src/Avalonia.Base/Data/Core/ExpressionObserver.cs

@ -78,7 +78,7 @@ namespace Avalonia.Data.Core
_node = node; _node = node;
Description = description; Description = description;
_root = new WeakReference(root); _root = new WeakReference<object>(root);
} }
/// <summary> /// <summary>
@ -120,7 +120,7 @@ namespace Avalonia.Data.Core
Contract.Requires<ArgumentNullException>(update != null); Contract.Requires<ArgumentNullException>(update != null);
Description = description; Description = description;
_node = node; _node = node;
_node.Target = new WeakReference(rootGetter()); _node.Target = new WeakReference<object>(rootGetter());
_root = update.Select(x => rootGetter()); _root = update.Select(x => rootGetter());
} }
@ -285,13 +285,13 @@ namespace Avalonia.Data.Core
if (_root is IObservable<object> observable) if (_root is IObservable<object> observable)
{ {
_rootSubscription = observable.Subscribe( _rootSubscription = observable.Subscribe(
x => _node.Target = new WeakReference(x != AvaloniaProperty.UnsetValue ? x : null), x => _node.Target = new WeakReference<object>(x != AvaloniaProperty.UnsetValue ? x : null),
x => PublishCompleted(), x => PublishCompleted(),
() => PublishCompleted()); () => PublishCompleted());
} }
else else
{ {
_node.Target = (WeakReference)_root; _node.Target = (WeakReference<object>)_root;
} }
} }

11
src/Avalonia.Base/Data/Core/IndexerExpressionNode.cs

@ -36,7 +36,9 @@ namespace Avalonia.Data.Core
{ {
try try
{ {
_setDelegate.DynamicInvoke(Target.Target, value); Target.TryGetTarget(out object target);
_setDelegate.DynamicInvoke(target, value);
return true; return true;
} }
catch (Exception) catch (Exception)
@ -64,6 +66,11 @@ namespace Avalonia.Data.Core
return _expression.Indexer == null || _expression.Indexer.Name == e.PropertyName; return _expression.Indexer == null || _expression.Indexer.Name == e.PropertyName;
} }
protected override int? TryGetFirstArgumentAsInt() => _firstArgumentDelegate.DynamicInvoke(Target.Target) as int?; protected override int? TryGetFirstArgumentAsInt()
{
Target.TryGetTarget(out object target);
return _firstArgumentDelegate.DynamicInvoke(target) as int?;
}
} }
} }

5
src/Avalonia.Base/Data/Core/IndexerNodeBase.cs

@ -13,9 +13,10 @@ namespace Avalonia.Data.Core
{ {
private IDisposable _subscription; private IDisposable _subscription;
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
var target = reference.Target; reference.TryGetTarget(out object target);
var incc = target as INotifyCollectionChanged; var incc = target as INotifyCollectionChanged;
var inpc = target as INotifyPropertyChanged; var inpc = target as INotifyPropertyChanged;
var inputs = new List<IObservable<object>>(); var inputs = new List<IObservable<object>>();

4
src/Avalonia.Base/Data/Core/Plugins/AvaloniaPropertyAccessorPlugin.cs

@ -31,12 +31,12 @@ namespace Avalonia.Data.Core.Plugins
/// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the
/// property will be made. /// property will be made.
/// </returns> /// </returns>
public IPropertyAccessor Start(WeakReference reference, string propertyName) public IPropertyAccessor Start(WeakReference<object> reference, string propertyName)
{ {
Contract.Requires<ArgumentNullException>(reference != null); Contract.Requires<ArgumentNullException>(reference != null);
Contract.Requires<ArgumentNullException>(propertyName != null); Contract.Requires<ArgumentNullException>(propertyName != null);
var instance = reference.Target; reference.TryGetTarget(out object instance);
var o = (AvaloniaObject)instance; var o = (AvaloniaObject)instance;
var p = LookupProperty(o, propertyName); var p = LookupProperty(o, propertyName);

23
src/Avalonia.Base/Data/Core/Plugins/DataAnnotationsValidationPlugin.cs

@ -15,9 +15,11 @@ namespace Avalonia.Data.Core.Plugins
public class DataAnnotationsValidationPlugin : IDataValidationPlugin public class DataAnnotationsValidationPlugin : IDataValidationPlugin
{ {
/// <inheritdoc/> /// <inheritdoc/>
public bool Match(WeakReference reference, string memberName) public bool Match(WeakReference<object> reference, string memberName)
{ {
return reference.Target? reference.TryGetTarget(out object target);
return target?
.GetType() .GetType()
.GetRuntimeProperty(memberName)? .GetRuntimeProperty(memberName)?
.GetCustomAttributes<ValidationAttribute>() .GetCustomAttributes<ValidationAttribute>()
@ -25,25 +27,22 @@ namespace Avalonia.Data.Core.Plugins
} }
/// <inheritdoc/> /// <inheritdoc/>
public IPropertyAccessor Start(WeakReference reference, string name, IPropertyAccessor inner) public IPropertyAccessor Start(WeakReference<object> reference, string name, IPropertyAccessor inner)
{ {
return new Accessor(reference, name, inner); return new Accessor(reference, name, inner);
} }
private class Accessor : DataValidationBase private sealed class Accessor : DataValidationBase
{ {
private ValidationContext _context; private readonly ValidationContext _context;
public Accessor(WeakReference reference, string name, IPropertyAccessor inner) public Accessor(WeakReference<object> reference, string name, IPropertyAccessor inner)
: base(inner) : base(inner)
{ {
_context = new ValidationContext(reference.Target); reference.TryGetTarget(out object target);
_context.MemberName = name;
}
public override bool SetValue(object value, BindingPriority priority) _context = new ValidationContext(target);
{ _context.MemberName = name;
return base.SetValue(value, priority);
} }
protected override void InnerValueChanged(object value) protected override void InnerValueChanged(object value)

8
src/Avalonia.Base/Data/Core/Plugins/ExceptionValidationPlugin.cs

@ -12,17 +12,17 @@ namespace Avalonia.Data.Core.Plugins
public class ExceptionValidationPlugin : IDataValidationPlugin public class ExceptionValidationPlugin : IDataValidationPlugin
{ {
/// <inheritdoc/> /// <inheritdoc/>
public bool Match(WeakReference reference, string memberName) => true; public bool Match(WeakReference<object> reference, string memberName) => true;
/// <inheritdoc/> /// <inheritdoc/>
public IPropertyAccessor Start(WeakReference reference, string name, IPropertyAccessor inner) public IPropertyAccessor Start(WeakReference<object> reference, string name, IPropertyAccessor inner)
{ {
return new Validator(reference, name, inner); return new Validator(reference, name, inner);
} }
private class Validator : DataValidationBase private sealed class Validator : DataValidationBase
{ {
public Validator(WeakReference reference, string name, IPropertyAccessor inner) public Validator(WeakReference<object> reference, string name, IPropertyAccessor inner)
: base(inner) : base(inner)
{ {
} }

5
src/Avalonia.Base/Data/Core/Plugins/IDataValidationPlugin.cs

@ -16,7 +16,7 @@ namespace Avalonia.Data.Core.Plugins
/// <param name="reference">A weak reference to the object.</param> /// <param name="reference">A weak reference to the object.</param>
/// <param name="memberName">The name of the member to validate.</param> /// <param name="memberName">The name of the member to validate.</param>
/// <returns>True if the plugin can handle the object; otherwise false.</returns> /// <returns>True if the plugin can handle the object; otherwise false.</returns>
bool Match(WeakReference reference, string memberName); bool Match(WeakReference<object> reference, string memberName);
/// <summary> /// <summary>
/// Starts monitoring the data validation state of a property on an object. /// Starts monitoring the data validation state of a property on an object.
@ -28,8 +28,7 @@ namespace Avalonia.Data.Core.Plugins
/// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the
/// property will be made. /// property will be made.
/// </returns> /// </returns>
IPropertyAccessor Start( IPropertyAccessor Start(WeakReference<object> reference,
WeakReference reference,
string propertyName, string propertyName,
IPropertyAccessor inner); IPropertyAccessor inner);
} }

3
src/Avalonia.Base/Data/Core/Plugins/IPropertyAccessorPlugin.cs

@ -28,8 +28,7 @@ namespace Avalonia.Data.Core.Plugins
/// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the
/// property will be made. /// property will be made.
/// </returns> /// </returns>
IPropertyAccessor Start( IPropertyAccessor Start(WeakReference<object> reference,
WeakReference reference,
string propertyName); string propertyName);
} }
} }

4
src/Avalonia.Base/Data/Core/Plugins/IStreamPlugin.cs

@ -15,7 +15,7 @@ namespace Avalonia.Data.Core.Plugins
/// </summary> /// </summary>
/// <param name="reference">A weak reference to the value.</param> /// <param name="reference">A weak reference to the value.</param>
/// <returns>True if the plugin can handle the value; otherwise false.</returns> /// <returns>True if the plugin can handle the value; otherwise false.</returns>
bool Match(WeakReference reference); bool Match(WeakReference<object> reference);
/// <summary> /// <summary>
/// Starts producing output based on the specified value. /// Starts producing output based on the specified value.
@ -24,6 +24,6 @@ namespace Avalonia.Data.Core.Plugins
/// <returns> /// <returns>
/// An observable that produces the output for the value. /// An observable that produces the output for the value.
/// </returns> /// </returns>
IObservable<object> Start(WeakReference reference); IObservable<object> Start(WeakReference<object> reference);
} }
} }

28
src/Avalonia.Base/Data/Core/Plugins/IndeiValidationPlugin.cs

@ -15,20 +15,25 @@ namespace Avalonia.Data.Core.Plugins
public class IndeiValidationPlugin : IDataValidationPlugin public class IndeiValidationPlugin : IDataValidationPlugin
{ {
/// <inheritdoc/> /// <inheritdoc/>
public bool Match(WeakReference reference, string memberName) => reference.Target is INotifyDataErrorInfo; public bool Match(WeakReference<object> reference, string memberName)
{
reference.TryGetTarget(out object target);
return target is INotifyDataErrorInfo;
}
/// <inheritdoc/> /// <inheritdoc/>
public IPropertyAccessor Start(WeakReference reference, string name, IPropertyAccessor accessor) public IPropertyAccessor Start(WeakReference<object> reference, string name, IPropertyAccessor accessor)
{ {
return new Validator(reference, name, accessor); return new Validator(reference, name, accessor);
} }
private class Validator : DataValidationBase, IWeakSubscriber<DataErrorsChangedEventArgs> private class Validator : DataValidationBase, IWeakSubscriber<DataErrorsChangedEventArgs>
{ {
WeakReference _reference; private readonly WeakReference<object> _reference;
string _name; private readonly string _name;
public Validator(WeakReference reference, string name, IPropertyAccessor inner) public Validator(WeakReference<object> reference, string name, IPropertyAccessor inner)
: base(inner) : base(inner)
{ {
_reference = reference; _reference = reference;
@ -45,7 +50,7 @@ namespace Avalonia.Data.Core.Plugins
protected override void SubscribeCore() protected override void SubscribeCore()
{ {
var target = _reference.Target as INotifyDataErrorInfo; var target = GetReferenceTarget() as INotifyDataErrorInfo;
if (target != null) if (target != null)
{ {
@ -60,7 +65,7 @@ namespace Avalonia.Data.Core.Plugins
protected override void UnsubscribeCore() protected override void UnsubscribeCore()
{ {
var target = _reference.Target as INotifyDataErrorInfo; var target = GetReferenceTarget() as INotifyDataErrorInfo;
if (target != null) if (target != null)
{ {
@ -80,7 +85,7 @@ namespace Avalonia.Data.Core.Plugins
private BindingNotification CreateBindingNotification(object value) private BindingNotification CreateBindingNotification(object value)
{ {
var target = (INotifyDataErrorInfo)_reference.Target; var target = (INotifyDataErrorInfo)GetReferenceTarget();
if (target != null) if (target != null)
{ {
@ -100,6 +105,13 @@ namespace Avalonia.Data.Core.Plugins
return new BindingNotification(value); return new BindingNotification(value);
} }
private object GetReferenceTarget()
{
_reference.TryGetTarget(out object target);
return target;
}
private Exception GenerateException(IList<string> errors) private Exception GenerateException(IList<string> errors)
{ {
if (errors.Count == 1) if (errors.Count == 1)

23
src/Avalonia.Base/Data/Core/Plugins/InpcPropertyAccessorPlugin.cs

@ -28,12 +28,12 @@ namespace Avalonia.Data.Core.Plugins
/// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the
/// property will be made. /// property will be made.
/// </returns> /// </returns>
public IPropertyAccessor Start(WeakReference reference, string propertyName) public IPropertyAccessor Start(WeakReference<object> reference, string propertyName)
{ {
Contract.Requires<ArgumentNullException>(reference != null); Contract.Requires<ArgumentNullException>(reference != null);
Contract.Requires<ArgumentNullException>(propertyName != null); Contract.Requires<ArgumentNullException>(propertyName != null);
var instance = reference.Target; reference.TryGetTarget(out object instance);
var p = instance.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name == propertyName); var p = instance.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name == propertyName);
if (p != null) if (p != null)
@ -50,11 +50,11 @@ namespace Avalonia.Data.Core.Plugins
private class Accessor : PropertyAccessorBase, IWeakSubscriber<PropertyChangedEventArgs> private class Accessor : PropertyAccessorBase, IWeakSubscriber<PropertyChangedEventArgs>
{ {
private readonly WeakReference _reference; private readonly WeakReference<object> _reference;
private readonly PropertyInfo _property; private readonly PropertyInfo _property;
private bool _eventRaised; private bool _eventRaised;
public Accessor(WeakReference reference, PropertyInfo property) public Accessor(WeakReference<object> reference, PropertyInfo property)
{ {
Contract.Requires<ArgumentNullException>(reference != null); Contract.Requires<ArgumentNullException>(reference != null);
Contract.Requires<ArgumentNullException>(property != null); Contract.Requires<ArgumentNullException>(property != null);
@ -69,7 +69,7 @@ namespace Avalonia.Data.Core.Plugins
{ {
get get
{ {
var o = _reference.Target; var o = GetReferenceTarget();
return (o != null) ? _property.GetValue(o) : null; return (o != null) ? _property.GetValue(o) : null;
} }
} }
@ -79,7 +79,7 @@ namespace Avalonia.Data.Core.Plugins
if (_property.CanWrite) if (_property.CanWrite)
{ {
_eventRaised = false; _eventRaised = false;
_property.SetValue(_reference.Target, value); _property.SetValue(GetReferenceTarget(), value);
if (!_eventRaised) if (!_eventRaised)
{ {
@ -109,7 +109,7 @@ namespace Avalonia.Data.Core.Plugins
protected override void UnsubscribeCore() protected override void UnsubscribeCore()
{ {
var inpc = _reference.Target as INotifyPropertyChanged; var inpc = GetReferenceTarget() as INotifyPropertyChanged;
if (inpc != null) if (inpc != null)
{ {
@ -120,6 +120,13 @@ namespace Avalonia.Data.Core.Plugins
} }
} }
private object GetReferenceTarget()
{
_reference.TryGetTarget(out object target);
return target;
}
private void SendCurrentValue() private void SendCurrentValue()
{ {
try try
@ -132,7 +139,7 @@ namespace Avalonia.Data.Core.Plugins
private void SubscribeToChanges() private void SubscribeToChanges()
{ {
var inpc = _reference.Target as INotifyPropertyChanged; var inpc = GetReferenceTarget() as INotifyPropertyChanged;
if (inpc != null) if (inpc != null)
{ {

21
src/Avalonia.Base/Data/Core/Plugins/MethodAccessorPlugin.cs

@ -9,12 +9,12 @@ namespace Avalonia.Data.Core.Plugins
public bool Match(object obj, string methodName) public bool Match(object obj, string methodName)
=> obj.GetType().GetRuntimeMethods().Any(x => x.Name == methodName); => obj.GetType().GetRuntimeMethods().Any(x => x.Name == methodName);
public IPropertyAccessor Start(WeakReference reference, string methodName) public IPropertyAccessor Start(WeakReference<object> reference, string methodName)
{ {
Contract.Requires<ArgumentNullException>(reference != null); Contract.Requires<ArgumentNullException>(reference != null);
Contract.Requires<ArgumentNullException>(methodName != null); Contract.Requires<ArgumentNullException>(methodName != null);
var instance = reference.Target; reference.TryGetTarget(out object instance);
var method = instance.GetType().GetRuntimeMethods().FirstOrDefault(x => x.Name == methodName); var method = instance.GetType().GetRuntimeMethods().FirstOrDefault(x => x.Name == methodName);
if (method != null) if (method != null)
@ -35,9 +35,9 @@ namespace Avalonia.Data.Core.Plugins
} }
} }
private class Accessor : PropertyAccessorBase private sealed class Accessor : PropertyAccessorBase
{ {
public Accessor(WeakReference reference, MethodInfo method) public Accessor(WeakReference<object> reference, MethodInfo method)
{ {
Contract.Requires<ArgumentNullException>(reference != null); Contract.Requires<ArgumentNullException>(reference != null);
Contract.Requires<ArgumentNullException>(method != null); Contract.Requires<ArgumentNullException>(method != null);
@ -61,8 +61,17 @@ namespace Avalonia.Data.Core.Plugins
var genericTypeParameters = paramTypes.Concat(new[] { returnType }).ToArray(); var genericTypeParameters = paramTypes.Concat(new[] { returnType }).ToArray();
PropertyType = Type.GetType($"System.Func`{genericTypeParameters.Length}").MakeGenericType(genericTypeParameters); PropertyType = Type.GetType($"System.Func`{genericTypeParameters.Length}").MakeGenericType(genericTypeParameters);
} }
Value = method.IsStatic ? method.CreateDelegate(PropertyType) : method.CreateDelegate(PropertyType, reference.Target); if (method.IsStatic)
{
Value = method.CreateDelegate(PropertyType);
}
else
{
reference.TryGetTarget(out object target);
Value = method.CreateDelegate(PropertyType, target);
}
} }
public override Type PropertyType { get; } public override Type PropertyType { get; }

12
src/Avalonia.Base/Data/Core/Plugins/ObservableStreamPlugin.cs

@ -20,9 +20,11 @@ namespace Avalonia.Data.Core.Plugins
/// </summary> /// </summary>
/// <param name="reference">A weak reference to the value.</param> /// <param name="reference">A weak reference to the value.</param>
/// <returns>True if the plugin can handle the value; otherwise false.</returns> /// <returns>True if the plugin can handle the value; otherwise false.</returns>
public virtual bool Match(WeakReference reference) public virtual bool Match(WeakReference<object> reference)
{ {
return reference.Target.GetType().GetInterfaces().Any(x => reference.TryGetTarget(out object target);
return target != null && target.GetType().GetInterfaces().Any(x =>
x.IsGenericType && x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IObservable<>)); x.GetGenericTypeDefinition() == typeof(IObservable<>));
} }
@ -34,9 +36,9 @@ namespace Avalonia.Data.Core.Plugins
/// <returns> /// <returns>
/// An observable that produces the output for the value. /// An observable that produces the output for the value.
/// </returns> /// </returns>
public virtual IObservable<object> Start(WeakReference reference) public virtual IObservable<object> Start(WeakReference<object> reference)
{ {
var target = reference.Target; reference.TryGetTarget(out object target);
// If the observable returns a reference type then we can cast it. // If the observable returns a reference type then we can cast it.
if (target is IObservable<object> result) if (target is IObservable<object> result)
@ -46,7 +48,7 @@ namespace Avalonia.Data.Core.Plugins
// If the observable returns a value type then we need to call Observable.Select on it. // If the observable returns a value type then we need to call Observable.Select on it.
// First get the type of T in `IObservable<T>`. // First get the type of T in `IObservable<T>`.
var sourceType = reference.Target.GetType().GetInterfaces().First(x => var sourceType = target.GetType().GetInterfaces().First(x =>
x.IsGenericType && x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IObservable<>)).GetGenericArguments()[0]; x.GetGenericTypeDefinition() == typeof(IObservable<>)).GetGenericArguments()[0];

13
src/Avalonia.Base/Data/Core/Plugins/TaskStreamPlugin.cs

@ -19,7 +19,12 @@ namespace Avalonia.Data.Core.Plugins
/// </summary> /// </summary>
/// <param name="reference">A weak reference to the value.</param> /// <param name="reference">A weak reference to the value.</param>
/// <returns>True if the plugin can handle the value; otherwise false.</returns> /// <returns>True if the plugin can handle the value; otherwise false.</returns>
public virtual bool Match(WeakReference reference) => reference.Target is Task; public virtual bool Match(WeakReference<object> reference)
{
reference.TryGetTarget(out object target);
return target is Task;
}
/// <summary> /// <summary>
/// Starts producing output based on the specified value. /// Starts producing output based on the specified value.
@ -28,11 +33,11 @@ namespace Avalonia.Data.Core.Plugins
/// <returns> /// <returns>
/// An observable that produces the output for the value. /// An observable that produces the output for the value.
/// </returns> /// </returns>
public virtual IObservable<object> Start(WeakReference reference) public virtual IObservable<object> Start(WeakReference<object> reference)
{ {
var task = reference.Target as Task; reference.TryGetTarget(out object target);
if (task != null) if (target is Task task)
{ {
var resultProperty = task.GetType().GetRuntimeProperty("Result"); var resultProperty = task.GetType().GetRuntimeProperty("Result");

6
src/Avalonia.Base/Data/Core/PropertyAccessorNode.cs

@ -37,9 +37,11 @@ namespace Avalonia.Data.Core
return false; return false;
} }
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference.Target, PropertyName)); reference.TryGetTarget(out object target);
var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(target, PropertyName));
var accessor = plugin?.Start(reference, PropertyName); var accessor = plugin?.Start(reference, PropertyName);
if (_enableValidation && Next == null) if (_enableValidation && Next == null)

18
src/Avalonia.Base/Data/Core/SettableNode.cs

@ -19,11 +19,25 @@ namespace Avalonia.Data.Core
{ {
return false; return false;
} }
if (LastValue == null)
{
return false;
}
bool isLastValueAlive = LastValue.TryGetTarget(out object lastValue);
if (!isLastValueAlive)
{
return false;
}
if (PropertyType.IsValueType) if (PropertyType.IsValueType)
{ {
return LastValue?.Target != null && LastValue.Target.Equals(value); return lastValue.Equals(value);
} }
return LastValue != null && Object.ReferenceEquals(LastValue?.Target, value);
return ReferenceEquals(lastValue, value);
} }
protected abstract bool SetTargetValueCore(object value, BindingPriority priority); protected abstract bool SetTargetValueCore(object value, BindingPriority priority);

2
src/Avalonia.Base/Data/Core/StreamNode.cs

@ -12,7 +12,7 @@ namespace Avalonia.Data.Core
public override string Description => "^"; public override string Description => "^";
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
foreach (var plugin in ExpressionObserver.StreamHandlers) foreach (var plugin in ExpressionObserver.StreamHandlers)
{ {

12
src/Avalonia.Input/Gestures.cs

@ -31,7 +31,7 @@ namespace Avalonia.Input
RoutedEvent.Register<ScrollGestureEventArgs>( RoutedEvent.Register<ScrollGestureEventArgs>(
"ScrollGestureEnded", RoutingStrategies.Bubble, typeof(Gestures)); "ScrollGestureEnded", RoutingStrategies.Bubble, typeof(Gestures));
private static WeakReference s_lastPress; private static WeakReference<IInteractive> s_lastPress;
static Gestures() static Gestures()
{ {
@ -47,11 +47,11 @@ namespace Avalonia.Input
if (e.ClickCount <= 1) if (e.ClickCount <= 1)
{ {
s_lastPress = new WeakReference(e.Source); s_lastPress = new WeakReference<IInteractive>(e.Source);
} }
else if (s_lastPress?.IsAlive == true && e.ClickCount == 2 && s_lastPress.Target == e.Source) else if (s_lastPress != null && e.ClickCount == 2 && e.MouseButton != MouseButton.Right)
{ {
if (e.MouseButton != MouseButton.Right) if (s_lastPress.TryGetTarget(out var target) && target == e.Source)
{ {
e.Source.RaiseEvent(new RoutedEventArgs(DoubleTappedEvent)); e.Source.RaiseEvent(new RoutedEventArgs(DoubleTappedEvent));
} }
@ -65,10 +65,10 @@ namespace Avalonia.Input
{ {
var e = (PointerReleasedEventArgs)ev; var e = (PointerReleasedEventArgs)ev;
if (s_lastPress?.IsAlive == true && s_lastPress.Target == e.Source) if (s_lastPress.TryGetTarget(out var target) && target == e.Source)
{ {
var et = e.MouseButton != MouseButton.Right ? TappedEvent : RightTappedEvent; var et = e.MouseButton != MouseButton.Right ? TappedEvent : RightTappedEvent;
((IInteractive)s_lastPress.Target).RaiseEvent(new RoutedEventArgs(et)); e.Source.RaiseEvent(new RoutedEventArgs(et));
} }
} }
} }

2
src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/ElementNameNode.cs

@ -19,7 +19,7 @@ namespace Avalonia.Markup.Parsers.Nodes
public override string Description => $"#{_name}"; public override string Description => $"#{_name}";
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
if (_nameScope.TryGetTarget(out var scope)) if (_nameScope.TryGetTarget(out var scope))
_subscription = NameScopeLocator.Track(scope, _name).Subscribe(ValueChanged); _subscription = NameScopeLocator.Track(scope, _name).Subscribe(ValueChanged);

4
src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/FindAncestorNode.cs

@ -31,9 +31,9 @@ namespace Avalonia.Markup.Parsers.Nodes
} }
} }
protected override void StartListeningCore(WeakReference reference) protected override void StartListeningCore(WeakReference<object> reference)
{ {
if (reference.Target is ILogical logical) if (reference.TryGetTarget(out object target) && target is ILogical logical)
{ {
_subscription = ControlLocator.Track(logical, _level, _ancestorType).Subscribe(ValueChanged); _subscription = ControlLocator.Track(logical, _level, _ancestorType).Subscribe(ValueChanged);
} }

26
src/Markup/Avalonia.Markup/Markup/Parsers/Nodes/StringIndexerNode.cs

@ -26,9 +26,11 @@ namespace Avalonia.Markup.Parsers.Nodes
protected override bool SetTargetValueCore(object value, BindingPriority priority) protected override bool SetTargetValueCore(object value, BindingPriority priority)
{ {
var typeInfo = Target.Target.GetType().GetTypeInfo(); Target.TryGetTarget(out object target);
var list = Target.Target as IList;
var dictionary = Target.Target as IDictionary; var typeInfo = target.GetType().GetTypeInfo();
var list = target as IList;
var dictionary = target as IDictionary;
var indexerProperty = GetIndexer(typeInfo); var indexerProperty = GetIndexer(typeInfo);
var indexerParameters = indexerProperty?.GetIndexParameters(); var indexerParameters = indexerProperty?.GetIndexParameters();
@ -53,7 +55,7 @@ namespace Avalonia.Markup.Parsers.Nodes
// Try special cases where we can validate indices // Try special cases where we can validate indices
if (typeInfo.IsArray) if (typeInfo.IsArray)
{ {
return SetValueInArray((Array)Target.Target, intArgs, value); return SetValueInArray((Array)target, intArgs, value);
} }
else if (Arguments.Count == 1) else if (Arguments.Count == 1)
{ {
@ -83,14 +85,14 @@ namespace Avalonia.Markup.Parsers.Nodes
else else
{ {
// Fallback to unchecked access // Fallback to unchecked access
indexerProperty.SetValue(Target.Target, value, convertedObjectArray); indexerProperty.SetValue(target, value, convertedObjectArray);
return true; return true;
} }
} }
else else
{ {
// Fallback to unchecked access // Fallback to unchecked access
indexerProperty.SetValue(Target.Target, value, convertedObjectArray); indexerProperty.SetValue(target, value, convertedObjectArray);
return true; return true;
} }
} }
@ -98,7 +100,7 @@ namespace Avalonia.Markup.Parsers.Nodes
// multidimensional indexer, which doesn't take the same number of arguments // multidimensional indexer, which doesn't take the same number of arguments
else if (typeInfo.IsArray) else if (typeInfo.IsArray)
{ {
SetValueInArray((Array)Target.Target, value); SetValueInArray((Array)target, value);
return true; return true;
} }
return false; return false;
@ -126,7 +128,15 @@ namespace Avalonia.Markup.Parsers.Nodes
public IList<string> Arguments { get; } public IList<string> Arguments { get; }
public override Type PropertyType => GetIndexer(Target.Target.GetType().GetTypeInfo())?.PropertyType; public override Type PropertyType
{
get
{
Target.TryGetTarget(out object target);
return GetIndexer(target.GetType().GetTypeInfo())?.PropertyType;
}
}
protected override object GetValue(object target) protected override object GetValue(object target)
{ {

2
tests/Avalonia.Base.UnitTests/Data/Core/ExpressionObserverTests_Property.cs

@ -574,7 +574,7 @@ namespace Avalonia.Base.UnitTests.Data.Core
var source = new Class1 { Foo = "foo" }; var source = new Class1 { Foo = "foo" };
var target = new PropertyAccessorNode("Foo", false); var target = new PropertyAccessorNode("Foo", false);
Assert.NotNull(target); Assert.NotNull(target);
target.Target = new WeakReference(source); target.Target = new WeakReference<object>(source);
target.Subscribe(_ => { }); target.Subscribe(_ => { });
target.Unsubscribe(); target.Unsubscribe();
target.Unsubscribe(); target.Unsubscribe();

14
tests/Avalonia.Base.UnitTests/Data/Core/Plugins/DataAnnotationsValidationPluginTests.cs

@ -20,7 +20,7 @@ namespace Avalonia.Markup.UnitTests.Data.Plugins
var target = new DataAnnotationsValidationPlugin(); var target = new DataAnnotationsValidationPlugin();
var data = new Data(); var data = new Data();
Assert.True(target.Match(new WeakReference(data), nameof(Data.Between5And10))); Assert.True(target.Match(new WeakReference<object>(data), nameof(Data.Between5And10)));
} }
[Fact] [Fact]
@ -29,7 +29,7 @@ namespace Avalonia.Markup.UnitTests.Data.Plugins
var target = new DataAnnotationsValidationPlugin(); var target = new DataAnnotationsValidationPlugin();
var data = new Data(); var data = new Data();
Assert.True(target.Match(new WeakReference(data), nameof(Data.PhoneNumber))); Assert.True(target.Match(new WeakReference<object>(data), nameof(Data.PhoneNumber)));
} }
[Fact] [Fact]
@ -38,7 +38,7 @@ namespace Avalonia.Markup.UnitTests.Data.Plugins
var target = new DataAnnotationsValidationPlugin(); var target = new DataAnnotationsValidationPlugin();
var data = new Data(); var data = new Data();
Assert.False(target.Match(new WeakReference(data), nameof(Data.Unvalidated))); Assert.False(target.Match(new WeakReference<object>(data), nameof(Data.Unvalidated)));
} }
[Fact] [Fact]
@ -47,8 +47,8 @@ namespace Avalonia.Markup.UnitTests.Data.Plugins
var inpcAccessorPlugin = new InpcPropertyAccessorPlugin(); var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
var validatorPlugin = new DataAnnotationsValidationPlugin(); var validatorPlugin = new DataAnnotationsValidationPlugin();
var data = new Data(); var data = new Data();
var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.Between5And10)); var accessor = inpcAccessorPlugin.Start(new WeakReference<object>(data), nameof(data.Between5And10));
var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.Between5And10), accessor); var validator = validatorPlugin.Start(new WeakReference<object>(data), nameof(data.Between5And10), accessor);
var result = new List<object>(); var result = new List<object>();
var errmsg = new RangeAttribute(5, 10).FormatErrorMessage(nameof(Data.Between5And10)); var errmsg = new RangeAttribute(5, 10).FormatErrorMessage(nameof(Data.Between5And10));
@ -79,8 +79,8 @@ namespace Avalonia.Markup.UnitTests.Data.Plugins
var inpcAccessorPlugin = new InpcPropertyAccessorPlugin(); var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
var validatorPlugin = new DataAnnotationsValidationPlugin(); var validatorPlugin = new DataAnnotationsValidationPlugin();
var data = new Data(); var data = new Data();
var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.PhoneNumber)); var accessor = inpcAccessorPlugin.Start(new WeakReference<object>(data), nameof(data.PhoneNumber));
var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.PhoneNumber), accessor); var validator = validatorPlugin.Start(new WeakReference<object>(data), nameof(data.PhoneNumber), accessor);
var result = new List<object>(); var result = new List<object>();
validator.Subscribe(x => result.Add(x)); validator.Subscribe(x => result.Add(x));

4
tests/Avalonia.Base.UnitTests/Data/Core/Plugins/ExceptionValidationPluginTests.cs

@ -19,8 +19,8 @@ namespace Avalonia.Base.UnitTests.Data.Core.Plugins
var inpcAccessorPlugin = new InpcPropertyAccessorPlugin(); var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
var validatorPlugin = new ExceptionValidationPlugin(); var validatorPlugin = new ExceptionValidationPlugin();
var data = new Data(); var data = new Data();
var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.MustBePositive)); var accessor = inpcAccessorPlugin.Start(new WeakReference<object>(data), nameof(data.MustBePositive));
var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.MustBePositive), accessor); var validator = validatorPlugin.Start(new WeakReference<object>(data), nameof(data.MustBePositive), accessor);
var result = new List<object>(); var result = new List<object>();
validator.Subscribe(x => result.Add(x)); validator.Subscribe(x => result.Add(x));

8
tests/Avalonia.Base.UnitTests/Data/Core/Plugins/IndeiValidationPluginTests.cs

@ -18,8 +18,8 @@ namespace Avalonia.Base.UnitTests.Data.Core.Plugins
var inpcAccessorPlugin = new InpcPropertyAccessorPlugin(); var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
var validatorPlugin = new IndeiValidationPlugin(); var validatorPlugin = new IndeiValidationPlugin();
var data = new Data { Maximum = 5 }; var data = new Data { Maximum = 5 };
var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.Value)); var accessor = inpcAccessorPlugin.Start(new WeakReference<object>(data), nameof(data.Value));
var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.Value), accessor); var validator = validatorPlugin.Start(new WeakReference<object>(data), nameof(data.Value), accessor);
var result = new List<object>(); var result = new List<object>();
validator.Subscribe(x => result.Add(x)); validator.Subscribe(x => result.Add(x));
@ -53,8 +53,8 @@ namespace Avalonia.Base.UnitTests.Data.Core.Plugins
var inpcAccessorPlugin = new InpcPropertyAccessorPlugin(); var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
var validatorPlugin = new IndeiValidationPlugin(); var validatorPlugin = new IndeiValidationPlugin();
var data = new Data { Maximum = 5 }; var data = new Data { Maximum = 5 };
var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.Value)); var accessor = inpcAccessorPlugin.Start(new WeakReference<object>(data), nameof(data.Value));
var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.Value), accessor); var validator = validatorPlugin.Start(new WeakReference<object>(data), nameof(data.Value), accessor);
Assert.Equal(0, data.ErrorsChangedSubscriptionCount); Assert.Equal(0, data.ErrorsChangedSubscriptionCount);
validator.Subscribe(_ => { }); validator.Subscribe(_ => { });

132
tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs

@ -60,6 +60,80 @@ namespace Avalonia.Markup.UnitTests.Data
Assert.Equal("baz", source.Foo); Assert.Equal("baz", source.Foo);
} }
[Fact]
public void TwoWay_Binding_Should_Be_Set_Up_GC_Collect()
{
var source = new WeakRefSource { Foo = null };
var target = new TestControl { DataContext = source };
var binding = new Binding
{
Path = "Foo",
Mode = BindingMode.TwoWay
};
target.Bind(TestControl.ValueProperty, binding);
var ref1 = AssignValue(target, "ref1");
Assert.Equal(ref1.Target, source.Foo);
GC.Collect();
GC.WaitForPendingFinalizers();
var ref2 = AssignValue(target, "ref2");
GC.Collect();
GC.WaitForPendingFinalizers();
target.Value = null;
Assert.Null(source.Foo);
}
private class DummyObject : ICloneable
{
private readonly string _val;
public DummyObject(string val)
{
_val = val;
}
public object Clone()
{
return new DummyObject(_val);
}
protected bool Equals(DummyObject other)
{
return string.Equals(_val, other._val);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((DummyObject) obj);
}
public override int GetHashCode()
{
return (_val != null ? _val.GetHashCode() : 0);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private WeakReference AssignValue(TestControl source, string val)
{
var obj = new DummyObject(val);
source.Value = obj;
return new WeakReference(obj);
}
[Fact] [Fact]
public void OneTime_Binding_Should_Be_Set_Up() public void OneTime_Binding_Should_Be_Set_Up()
{ {
@ -568,12 +642,70 @@ namespace Avalonia.Markup.UnitTests.Data
} }
} }
public class WeakRefSource : INotifyPropertyChanged
{
private WeakReference<object> _foo;
public object Foo
{
get
{
if (_foo == null)
{
return null;
}
if (_foo.TryGetTarget(out object target))
{
if (target is ICloneable cloneable)
{
return cloneable.Clone();
}
return target;
}
return null;
}
set
{
_foo = new WeakReference<object>(value);
RaisePropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
private class OldDataContextViewModel private class OldDataContextViewModel
{ {
public int Foo { get; set; } = 1; public int Foo { get; set; } = 1;
public int Bar { get; set; } = 2; public int Bar { get; set; } = 2;
} }
private class TestControl : Control
{
public static readonly DirectProperty<TestControl, object> ValueProperty =
AvaloniaProperty.RegisterDirect<TestControl, object>(
nameof(Value),
o => o.Value,
(o, v) => o.Value = v);
private object _value;
public object Value
{
get => _value;
set => SetAndRaise(ValueProperty, ref _value, value);
}
}
private class OldDataContextTest : Control private class OldDataContextTest : Control
{ {
public static readonly StyledProperty<int> FooProperty = public static readonly StyledProperty<int> FooProperty =

Loading…
Cancel
Save