The binding path parser built type names with ParseIdentifier, which doesn't
accept '+', so a cast like ((local:Outer+Nested)DataContext) stopped parsing at
the '+' and then failed expecting a ')'. Parse type names with a variant that
accepts '+'. Ordinary identifiers are unchanged.
* Update ncrunch config.
* Initial groundwork for typed binding expressions.
- Moved a bunch of stuff from `UntypedBindingExpressionBase` to `BindingExpressionBase`
- Make various APIs accept `BindingExpressionBase` instead of `UntypedBindingExpressionBase`
- Added a typed `IPropertyInfo`
- Added a method on the `CompiledBindingPathBuilder` to build typed property accessors
- Initial basic implementation of `TypedBindingExpression`
* Track values in typed binding expression.
* Support binding mode in typed binding expression.
* Add typed binding expression benchmarks.
Add Setup/Values benchmarks comparing the typed binding expression
against the untyped CompiledBinding (as emitted by the XAML compiler
today) and the reflection-based Binding.
Writing the benchmarks surfaced that TypedBindingExpression never
detached: it had no Dispose override, so disposing a binding (or
rebinding the same property) leaked its PropertyChanged subscriptions
and left it registered in the value store. Wire up disposal mirroring
UntypedBindingExpressionBase: stop, detach handlers, remove from the
value store and frame. This required widening
IBindingExpressionSink.OnCompleted from UntypedBindingExpressionBase to
BindingExpressionBase. Also fix a nullable warning that broke the
Release build.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@
* Don't box value in IBindingExpressionSink.OnChanged.
Instead notify the sink of what's changed and let the sink read the value boxed or unboxed.
* Move `IValueEntry` to `BindingExpressionBase`
* Fall back to BindingExpression.
Make `TypedPropertyElement` derive from `PropertyElement` and fall back to creating a standard boxing `BindingExpression` if any of the requirements for a typed binding expression are not met.
* Don't use typed expressions for DataContext.
* Emit typed binding expression from XAML compiler.
When a compiled binding path is shape-eligible (single CLR property on a
reference-type source, no transforms, instance getter) the compiler now
emits a call to the typed CompiledBindingPathBuilder.Property<TSource,
TResult> overload, producing a TypedPropertyElement that the runtime
turns into a non-boxing TypedBindingExpression<TSource, TValue>. Other
shapes continue to use the existing untyped emission path, and runtime
fallback to BindingExpression still kicks in when modifiers (Source,
Converter, StringFormat, etc.) make the typed expression unsuitable.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add failing tests for TwoWay typed binding source echo.
TypedBindingExpression writes the source value back to the source both on
attach and whenever the source raises a change: pushing the value to the
target re-enters OnTargetPropertyChanged, which (in TwoWay mode) calls
WriteValueToSource with the value that just arrived from the source.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Don't echo source value back to source in TwoWay typed binding.
When TypedBindingExpression pushed the source value to the target, the
resulting target PropertyChanged re-entered OnTargetPropertyChanged which,
in TwoWay mode, wrote the value straight back to the source - a redundant
round-trip on every attach and every source-originated change.
Guard the source->target push with a flag and skip WriteValueToSource while
it is set, so only genuine target changes are written back to the source.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Address typed binding code-review follow-ups.
- Reset _isRunning when a typed binding is unsubscribed so the expression
can be restarted (and re-subscribe to its source) if the value store
reactivates the entry later, matching UntypedBindingExpressionBase.Stop().
- Remove a stray `using static PropertySetSnapshot` import.
- Extract the duplicated IValueEntry value-unwrapping logic (shared by
EffectiveValue<T> and DirectPropertyBase) into IValueEntry.TryGetValue.
- Drop the unreachable UpdateSourceTrigger NotSupportedException in
CreateTypedExpression; CanUseTypedBindingExpression already constrains it.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Fix TypedBinding_Values benchmark build error.
The typed binding path was built with a single-argument `Property(propertyInfo)`
call, which has no matching overload, so the benchmark project did not compile.
Use the same typed three-argument overload as TypedBinding_Setup so the benchmark
exercises the TypedPropertyElement path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Skip typed binding expression for data-validation properties.
TypedBindingExpression does not support data validation, but the eligibility
check didn't account for it, so a directly-assignable single-property DataContext
binding to a validation-enabled target (e.g. TextBox.Text, NumericUpDown.Value)
would take the typed path and silently drop validation errors.
Fall back to the untyped BindingExpression when the target property enables data
validation. Data validation support in the typed expression can be added as a
follow-up.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Clarify that data validation is not supported.
* Address typed binding review comments.
- React to null/empty PropertyChanged.PropertyName ("all properties
changed") in the typed expression, matching the untyped path.
- Swallow source getter exceptions raised during PropertyChanged.
- Fall back to the untyped path for non-StyledElement targets, read-only
sources and wider target types in TwoWay/OneWayToSource modes.
- Fix a stray space in an exception message.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Share TypedBindingExpression.Attach validation across instantiations.
Factor the validation logic (most notably the exception string
formatting) out of the generic Attach method into a non-generic static
helper. It only uses typeof(TValue), not TValue, so sharing it avoids
duplicating the code per generic instantiation, a meaningful NativeAOT
size saving (~3.3 KB => ~2.5 KB per instantiation).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Update API suppressions.
These APIs are in a `[PrivateApi]`.
* Use cached boolean boxes in typed binding expression.
Merging main brought in the cached boxed booleans emitted for compiled
binding property getters (#21065), but bindings that now take the typed
binding expression path don't go through that getter: the value is boxed
in TypedBindingExpression.GetUntypedValue when the target property isn't
strongly typed (e.g. binding a bool to TextBlock.Tag). Box booleans via a
shared cache there too, restoring the no-allocation-per-read behaviour.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QkxawATDHa6rbPaDmPCLHZ
* Extract the whole TypedBindingExpression.Attach body into AttachCore.
3198196b4c only factored out the validation, leaving the field
assignments in the generic method. As MrJul pointed out, none of those
assignments depend on TSource or TValue either, so the entire body can
move into a method that doesn't reference the generic parameters and be
shared across instantiations rather than duplicated per instantiation.
Attach is now just a forwarder passing typeof(TValue) as a Type, and
AttachCore reads _sink/TargetProperty directly instead of having them
threaded through as parameters, which reads better than the previous
split.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QkxawATDHa6rbPaDmPCLHZ
* Move the method alongside the other privates.
* Add failing tests for typed binding expression breaking changes.
Each test binds the same property twice: once via a path which produces a
TypedBindingExpression and once via a path which produces an untyped
BindingExpression. The assertions describe the untyped behaviour, so the
typed cases fail where the typed expression diverges:
- A binding with no value (null or incompatible DataContext) publishes the
target property's default value at the binding's priority instead of not
contributing a value, overriding style setters and breaking inheritance.
- Writing a value of another type, or null, to an object-typed target
property throws from OnTargetPropertyChanged.
- No binding error is logged when the DataContext is of the wrong type.
- A throwing source getter leaves the stale value in place.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B66teLaFQBr9GJe4a1aTZm
* Fix typed binding expression divergences from the untyped path.
- Don't notify when the expression has no value and had none before: doing
so pushed the target property's default value at the binding's priority,
overriding style setters and breaking property inheritance.
- Read the target property's new value defensively. The binding value type
only needs to be assignable to the target property type, so the property
can hold a value which isn't a TValue; casting it threw out of the caller's
SetValue.
- Log a binding error when the DataContext can't be converted to the source
type, and when the source getter throws. The getter also now clears the
value rather than leaving the stale one in place.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B66teLaFQBr9GJe4a1aTZm
* Pass correct priority to child bindings.
The priority here doesn't actually have any effect as the binding isn't in a value store, but there's no reason to not use the correct one.
* Use the typed overload.
* Set initial priority to default priority.
Makes `TypedBindingExpressionBase` and `UntypedBindingExpressionBase` have the same behavior here.
* Remove unused vars.
* We now have a typed value here.
* Publish typed binding values on the UI thread.
The source's PropertyChanged event can be raised on any thread, so marshal
the notification to the UI thread as UntypedBindingExpressionBase does.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1ZwmCJkThPSeViLnRxoYs
* Share the property info cache lookup.
Emit and EmitTyped had identical cache lookups, differing only in which
dictionary they searched. Also delay constructing the generic types in
EmitTyped until a cache miss, as they aren't needed on a hit.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1ZwmCJkThPSeViLnRxoYs
* Share the property accessor delegate emission.
EmitFunc was duplicated as a local function in both Emit and EmitTyped.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1ZwmCJkThPSeViLnRxoYs
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Add failing test for boxed booleans in compiled binding getters
Compiled-binding getters for bool properties emit 'box' on every read,
allocating a fresh object each time (#21065 reports ~300K allocations in
a real app). Add BooleanBoxes with two cached boxed values and a test
asserting that a compiled binding to a bool property produces the cached
box instances. BooleanBoxes must be public because compiled XAML IL is
emitted into user assemblies, which need to reference its fields.
* Reuse cached boxed booleans in compiled binding getters
Instead of emitting 'box bool' in the generated property-info getter,
emit a branch that returns BooleanBoxes.True or BooleanBoxes.False, so
reads of bool properties through compiled bindings no longer allocate.
Other value types keep the existing box. Applies to both the build-time
XAML compiler and the runtime XAML loader, which share this emitter.
Fixes#21065
* fix: emit cached boolean boxes into the generated per-assembly helper
The cached boxed booleans used by compiled-binding bool getters were
exposed as a new public BooleanBoxes class in Avalonia.Base, adding
public API surface that is useful only to compiled XAML. Review asked
for the boxes to stay an implementation detail instead.
Define two private static fields and a static constructor on the
XamlIlHelpers type the XAML compiler already generates into each user
assembly, and point the getter IL at those. The fields are shared by
all XAML files in the assembly, so allocation behaviour is unchanged
while no public API is added. The test now asserts box identity across
repeated reads instead of referencing the removed class.
* Allow single parameter with any type when binding to method
* Port method binding logic to ReflectionBinding
* Don't depend on the order of methods
* Handle overrides properly
* Fix nullability warning
* Update to xunit.v3
* Little more progress
* More fixes
* Keep VSTest supported
* Adjust Nuke
* Few fixes
* Fix for xunit 2
* Fix GetData override
* Adjust
* Use MTP for xunit 2
* Fix test
* Better fix
* --no-progress
* Few more fixes
* no progress
* Fix test
* Better fix
* TRX
* Move to Directory.Build.props
* Unify on MTP v2
* Update
* Update to stable
* 1.0.1
* 1.0.2
* Fix some warnings
* Fix more warnings
* Fix more warnings
* Update ncrunch config.
* Tidy up reflection and multi-binding APIs:
- Move `BindingBase` and `MultiBinding` into Avalonia.Base
- `BindingBase` becomes a true base class for all bindings, and contains only the `Instance` method
- Properties common between reflection and compiled bindings are moved into `StandardBindingBase`
- `Binding` is moved to Avalonia.Base and renamed to `ReflectionBinding`
- A compatibility shim for `Binding` remains in Avalonia.Markup
- Remove `IBinding` and `IBinding2`
- Remove `ITreeDataTemplate's usage of `InstancedBinding`
- Remove `NativeMenuBarPresenter`s usage of `InstancedBinding`
- Remove `InstancedBinding` as it is now unused
This required an update to the DataGrid submodule: cell data validation has been temporarily removed as this used `InstancedBinding`.
* `Instance()` => `CreateInstance()`.
The use of "Instance" as a verb is quite unusual apparently ;)
* Seal classes where appropriate.
* Seal classes where appropriate.
* Remove `StandardBindingBase`.
Simply duplicate the members in reflection and compiled binding classes.
* Delete deleted submodule directory.
* Add missing attribute.
Fixes compile error.
* Fix reference to removed class.
* Update suppressions.
* Fix XamlTypeExtensionNode not being handled on the x:DataType transformer
* Add testt with complex DataType
* Make vm:MainWindowViewModel+TestItem nested type generic on BindingDemo
* Try to infer DataContext type from #named binding nodes
* Try to infer DataContext type from $parent binding nodes
* Use new syntax in the repo (Rider still marks it as an error)
* Add tests ensuring type casing still works
* Fix $parent regression
* Make new tests StringSyntax compatible
* Add failing test for #16113.
* Convert delegate to ICommand in style setter.
When compiling a binding to e.g. `Button.Command` in a style `Setter`, we were not converting `XamlIlClrMethodPathElementNode` to `XamlIlClrMethodAsCommandPathElementNode` as we were only testing whether the property that the binding was being assigned to is an `ICommand`.
If we detect that we're assigning the binding to a `Setter.Value` then we need to look in the `Setter.Property` to see check whether the property is an `ICommand` too.
Fixes#16113
* Update ncrunch config.
* Add tests for converting strings to brushes.
* Make complied bindings use TypeConverters.
Certain conversions rely on type converters, which were disabled in compiled bindings since #13970 due to warnings that type converters are not trimming friendly.
Ideally we'd be generating the type conversion logic in the XAML compiler, but in reality the problem with type converters and trimming is limited to type converters with generics, which is an edge case.
For the moment re-enable the usage of type converters in compiled bindings until we implement generating the conversion code in the XAML compiler.
* Added failing tests for #14456.
And one passing test.
* Handle converted compiled binding nodes...
...without a path. Previously the `convertedNode` was being discarded if the binding node had no arguments or property value assignments.
Fixes#14456
* Update ncrunch config.
* WIP: Benchmarks
* Initial refactor of binding infrastructure.
- `ExpressionObserver` has been removed and its functionality merged with `BindingExpression`
- `BindingExpression` handles all types of `BindingMode` itself; doesn't require `BindingOperations.Apply` to set up a separate observable for `TwoWay/`OneWayToSource` bindings
- This allows us to fix some long-standing issues with `OneWayToSource` bindings
- Expression nodes have been refactored
- No longer split between `Avalonia.Base` and `Avalonia.Markup`
- Categorize them according to whether they use reflection or not
A few tests are failing around binding warnings: this is because the next step here is to fix binding warnings.
* Make default binding Source = UnsetProperty.
Null is a theoretically valid value for `Source`; setting it to null shouldn't mean "use the data context".
* Move logging to BindingExpression.
As `BindingExpression` now has enough information to decide when it's appropriate to log an error/warning or not.
Fixes#5762Fixes#9422
* Add compatibility hack for older compiled bindings.
Previously, `CompiledBindingPathBuilder` didn't have a `TemplatedParent` method and instead the XAML compiler rewrite templated parent bindings to be a `$self.TemplateParent` property binding. resulting in extraneous logs.
Add a constructor with an `apiVersion` to `CompiledBindingPathBuilder` which will be used by newer versions of the XAML compiler, and if a usage is detected using an `apiVersion` of 0, then upgrade `$self.TemplatedParent` to use a `TemplatedParentPathElement`.
* Log errors from property accessors.
* Don't log errors for named control bindings...
...on elements which aren't yet rooted.
* Log errors for failed conversions.
* Use consistent wording for binding warnings.
"Could not convert" instead of "Cannot convert".
* Log warnings for converter exceptions.
* Don't convert new TargetTypeConverters each time.
* Added failing test for implicit conversion.
* Support cast operators in compiled bindings.
A bit of a hack as we'd ideally not be using reflection when using compiled bindings.
* This shouldn't be a public API.
Should only be used for tests.
* Make enum/int conversion work.
* Check for SetValue equality after conversion.
And also use "identity equals" where value types and strings use `object.Equals` and reference types use `object.ReferenceEquals`.
* Added ConverterCulture back to bindings.
* Fix merge error.
Removed deleted files from csproj that were re-added due to indentation changes.
* Use BindingExpression directly in ValueStoe.
* Introduce BindingExpressionBase.
And `UntypedBindingExpressionBase`.
* Make TemplateBinding a BindingExpression.
* Make DynamicResource use a BindingExpression.
* WIP: Start exposing a BindingExpression API.
* Finish exposing a BindingExpression API.
* Fix OneTimeBinding.
* Remove unneeded classes/methods.
* Don't call obsolete API.
* Make BindingExpressionBase the public API.
This matches WPF's API.
* Added BindingExpressionBase.UpdateTarget.
* Initial implementation of UpdateSourceTrigger.
* Don't use weak references for values.
If they're boxed values, they can get collected.
* No need for virtual/generic methods here now.
* Reintroduce support for binding anchors.
Turns out these were needed by animations, just our animation system has no unit tests so I missed that fact earlier. Add a basic animation unit test that fails without anchor support, and add binding anchors back in. Currently a private API as I suspect this feature shouldn't be needed outside the framework.
* Include new property in clone.
And add real-life example of `UpdateSourceTrigger=LostFocus` to BindingDemo.
* Fix merge error.
* Updated BindingExpression tests.
- Make them run for both compiled and reflection bindings (found a bunch of tests that fail with compiled bindings)
- Make them not depend on converting the `BindingExpression` to an observable and instead test the end result of the binding on an `AvaloniaObject`
* Fix compiled binding indexer tests.
* Use data validation plugins in PropertyAccessorNode.
Added a warning suppression for now: we may need a separate `DataValidators` list for AOT-friendly plugins.
* Don't separate plugins by reflection.
`DataAnnotationsValidationPlugin` is public and so it can't be moved. No point in moving the others if this one will be in the wrong place.
* Remove unneeded methods.
* Make reflection binding tests use a string.
Convert the `System.Linq.Expression` to a string and then use this, as reflection bindings will always be instanced with a string path.
* Added TODO12 plan for IBinding2.
* Use more specific exception.
* Fix nits from code review.
* Make expression nodes sealed where possible.
* Unsubscribe on Stop, don't re-subscribe.
D'oh.
* Tweak ExpressionNode lists.
Saves a few K in benchmarks and it's a cleaner API.
* Add a pooled option in BindingExpressionGrammar.
Micro-optimization.
* Avoid allocations when enumerating binding plugins.
* Add IBinding2 support to observable bind overloads.
In the case of `TemplateBinding`, the `IObservable<object?>` bind overload is selected by C#. Add an explicit check for an `IBinding2` here to use the more performant code-path.
* Remove disposed binding from ImmediateBindingFrame.
* Added TemplateBinding benchmarks.
* Remove duplicate items.
Seems to have been caused by a merge error.
* Fix exception when closing color picker.
And add tests.
* Don't skip converter when binding to self.
* Don't pass UnsetValue to converters.
This follows WPF behavior.
* Log element name if present.
More useful than just logging the control hash code.
* Respect binding priority.
* Throw on mismatched binding priorities.
We don't want to respect the binding priority in this case as it breaks `TemplateBindings` when the default `LocalValue` priority is passed. Instead make sure that the priority parameter matches that of the expression.
This reverts commit a72765d705.
* Convert to target type in TemplateBinding.
* Short-circuit target type conversion for same types.
* Add diagnostics support to the Avalonia.Build.Tasks
* HostApp and generators build fix
* Diagnostics support in Avalonia XAML
* Support multiple style selector errors at once
* Improve avalonia intrinsics error handling + add tests
* Add CompiledBindings multiple errors tests
* Fix name generator
* Make AvaloniaXamlIlDuplicateSettersChecker a warning
* Fix Style_Parser_Throws_For_Duplicate_Setter test
* Make XamlLoaderUnreachable respect warnings settings
* Add AvaloniaXamlIlStyleValidatorTransformer
* Throw more specific exceptions instead of XamlParseException
* Get rid of XamlXDiagnosticCode to simplify diagnostics code
* Simplify XAML exceptions by avoiding DiagnosticCode in them
* Simplify XamlCompilerDiagnosticsFilter
* Don't use AvaloniaXamlDiagnosticCodes in Avalonia.Generators
* Fix some error handlings in compiler task
* Update editor config for in-solution analysis
* Update XamlX
* Fix missing document path
* Avoid Description field usage
* Add AvaloniaXamlVerboseExceptions property and make exception formatting customizable
* Make Avalonia.NameGenerator not crash if there are XAML errors, members should still be generated
* Update tests/Avalonia.Markup.Xaml.UnitTests/Xaml/StyleIncludeTests.cs
---------
Co-authored-by: Jumar Macato <16554748+jmacato@users.noreply.github.com>
* Modernized accessor syntax in several places
* Toned down the getter modernization
* Block body for properties with code
---------
Co-authored-by: Lehonti Ramos <lehonti@ramos>
`ItemsControl` now works more like WPF, in that there are separate `Items` and `ItemsSource` properties. For backwards compatibility `Items` can still be set, though the setter is deprecated. `Items` needed to be changed from `IEnumerable` to `IList` though.
- Removes the `IStyler` service and the `Styler` implementation
- Moves the logic for applying styles and control themes into `StyledElement`
- Removes the style `TryAttach` method from the public API
- Removes style caching for now - this will need to be added back