[Proposal] Compiling typed bindings using source generators #20574
Labels
area-xaml
XAML, CSS, Triggers, Behaviors
fixed-in-9.0.0-preview.5.24307.10
proposal/open
t/enhancement ☀️
New feature or request
Milestone
Description
This is an alternative proposal to #19912
I've been thinking about ways to expose the type-safe and trimming-safe
TypedBinding<TSource, TProperty>
to all developers. Earlier, I explored the possibility of constructing typed bindings from expressions. This approach works (surprisingly) well and it is both type safe and trimming safe (PoC: #19995). The downside of the expression-based approach is the cost of transforming the expression into the typed binding instance. This takes both longer and allocates more memory than constructing the TypedBinding instance directly and parsing the path string.The .NET runtime team solved a similar issue with Regex in .NET 7 using source generators. Instead of parsing and compiling the regex pattern string at runtime, they added a new attribute
[GeneratedRegex("...")]
that allowed them to precompile the regex.I took inspiration from the regex work and applied it to bindings.
Public API Changes
We would need a new public attribute:
Intended Use-Case
Developers will create getter methods (convertible into
Func<TSource, TProperty>
) and applying the new attribute with some optional defaults. The generator will generate a factory method that will either be called${GetterMethodName}Binding}
or alternatively the developer can specify the name of the member through an attribute argument:The generated code for the app code would look something like this:
Relative binding sources
The relative binding sources could be defined this way:
The source generator would use this information to set
Source
:Alternative design
@StephaneDelcroix suggested using a simpler API, closer to the one from #19912:
This method would be intercepted by a source generator or XamlC and we would generate the code that creates the right
TypedBinding<TSource, TProperty> binding
instance and callsself.SetBinding(property, binding)
.The text was updated successfully, but these errors were encountered: