[Fact]
public void Coerce_AttachedProperty()
var numberOfCall = 0;
AttachedPropertyOwnerCoerce.CoerceDoubleCallback = (_) => numberOfCall++;
var class1 = new Class1();
class1.SetValue(AttachedPropertyOwnerCoerce.DoubleProperty, 101.1d);
Assert.Equal(1, numberOfCall);
Assert.Equal(100d, AttachedPropertyOwnerCoerce.GetDouble(class1));
private class AttachedPropertyOwnerCoerce
public static readonly AttachedProperty<double> DoubleProperty =
AvaloniaProperty.RegisterAttached<AttachedPropertyOwnerCoerce, Class1, double>("Double",coerce: CoerceDouble);
public static Action<AvaloniaObject> CoerceDoubleCallback;
public static double GetDouble(Class1 control) => control.GetValue(DoubleProperty);
public static void SetDouble(Class1 control, double value) => control.SetValue(DoubleProperty, value);
private static double CoerceDouble(AvaloniaObject instance, double value)
CoerceDoubleCallback?.Invoke(instance);
var o = (Class1)instance;
return Math.Clamp(value, 50d, 100d);
Run Coerce_AttachedProperty
test
See error
Expected behavior
Coercion Callback is invoked
Screenshots
(none)
Desktop (please complete the following information):
OS: any
Version: 11.0.0-preview7
Additional context
Add any other context about the problem here.
Validate Callback is invoked
AvaloniaProperty.RegisterAttached
creates an AttachedProperty
object and tells it about TOwner
. That's type which is registering the attached property, i.e. AttachedPropertyOwnerCoerce
in the sample code above.
But when the value is set, metadata for the target AvaloniaObject
is resolved. In this case, the target object is a Class1
. Because Class1
is not compatible with AttachedPropertyOwnerCoerce
, no metadata is found and the default metadata is used. Due to #10572, this default metadata object no longer includes the coercion method.
Is it correct to create the attached property with TOwner
? Giving it THost
instead would fix this bug. I'm not sure why the property object would ever need to know about TOwner
, which does not have to be an AvaloniaObject
and is often static.
AttachedPropertyOwnerCoerce
is common scenario and it use to extend the behavior of DependencyObject.
TOwner
is where the Set* and Get methods are defined.
What is the advantage of TOwner
deriving from AvaloniaObject?
I'm talking above about the internal behaviour of RegisterAttached
. There is nothing wrong with the test class you posted.
sorry, i misunderstanding. Can you give me how to search to try and fix the problem?
AttachedProperty Corece Callback is not invoked
AttachedProperty Coercion Callback is not invoked
May 11, 2023