ExpressionBinding.Avalonia brings inline, expression-backed MultiBinding support to Avalonia XAML without writing boilerplate IMultiValueConverter classes or generating code per binding site.
An embedded source-generated Parlot parser turns each expression into an immutable syntax tree once, compiles a fixed LINQ expression control-flow plan, and uses DLR call sites to resolve operators, implicit conversions, and function overloads dynamically from the runtime argument types with second-level caching.
- Zero boilerplate XAML expressions: Combine any mix of
CompiledBinding,ReflectionBinding,DynamicResource, or constant values using positional argumentsAthroughZ. - Rich C#-inspired syntax: Supports arithmetic, bitwise, shift, comparison, logical short-circuiting (
&&/||), conditional (?:), andswitchexpressions with relational/discard/orpatterns andwhenguards. - Avalonia-native binding semantics: Properly handles
BindingOperations.DoNothingandAvaloniaProperty.UnsetValue(unsetliteral & sentinel propagation). - Extensible function registries: Register closed delegates, static method groups, or
MethodInfoentries (includingparams T[]and open generic inference) globally or per-view. - NativeAOT compatible: Automatically uses the LINQ expression interpreter when dynamic code generation is unavailable; the Parlot parser is source-generated with zero runtime parser dependency.
- Broad compatibility: Targets
net8.0,net10.0, andnet11.0against Avalonia12.0.0+.
dotnet add package ExpressionBinding.AvaloniaDeclare the XML namespace on your root view or control:
xmlns:expression="using:ExpressionBinding.Avalonia"
xmlns:system="clr-namespace:System;assembly=System.Runtime"Then author an expression directly on any bindable property:
<TextBlock.FontSize>
<expression:ExpressionBinding Expression="min(3 * A, B) + 24">
<DynamicResource ResourceKey="FontSize3Xl" />
<ReflectionBinding>
<ReflectionBinding.Source>
<system:Double>64</system:Double>
</ReflectionBinding.Source>
</ReflectionBinding>
</expression:ExpressionBinding>
</TextBlock.FontSize>- Positional identifiers
AthroughZ(case-sensitive) map in order to child items inArguments. - Child items may be any Avalonia
BindingBaseor a literal/object value (non-binding objects are automatically wrapped in a one-wayCompiledBinding). ExpressionBindingalways produces a one-wayMultiBinding.
Tip
Inside XML attribute strings (Expression="..."), use single quotes ('...') for string literals and XML-escape < / & as < / & (for example < 520 and &&).
Compute padding, corner radii, or clamped panel widths directly from dynamic theme resources and live bounds:
<!-- Auto-center icon padding from two theme font-size tokens -->
<Button Height="{DynamicResource FontSize3Xl}">
<Button.Padding>
<expression:ExpressionBinding Expression="thickness((A - B) / 2)">
<DynamicResource ResourceKey="FontSize3Xl" />
<DynamicResource ResourceKey="FontSizeXl" />
</expression:ExpressionBinding>
</Button.Padding>
</Button>
<!-- Clamp a responsive card width between 280 and 720 -->
<Border>
<Border.Width>
<expression:ExpressionBinding Expression="clamp(A * 0.85, 280, 720)">
<Binding Path="$parent[Window].Bounds.Width" />
</expression:ExpressionBinding>
</Border.Width>
</Border>Replace one-off multi-value boolean converters with short-circuit logic and ternary expressions:
<!-- Enable Submit only when not busy, items exist, and terms are accepted -->
<Button Content="Submit">
<Button.IsEnabled>
<expression:ExpressionBinding Expression="!A && B > 0 && C">
<Binding Path="IsBusy" />
<Binding Path="Items.Count" />
<Binding Path="HasAcceptedTerms" />
</expression:ExpressionBinding>
</Button.IsEnabled>
<Button.Opacity>
<expression:ExpressionBinding Expression="A ? 0.5 : 1.0">
<Binding Path="IsBusy" />
</expression:ExpressionBinding>
</Button.Opacity>
</Button>Use switch expressions with relational patterns, or patterns, and when guards for adaptive layouts or state badges:
<!-- Adaptive grid columns based on container width -->
<UniformGrid>
<UniformGrid.Columns>
<expression:ExpressionBinding Expression="A switch { < 520 => 1, < 960 => 2, _ => 3 }">
<Binding Path="$parent[UserControl].Bounds.Width" />
</expression:ExpressionBinding>
</UniformGrid.Columns>
</UniformGrid>
<!-- Map status codes with single-quoted strings -->
<TextBlock>
<TextBlock.Text>
<expression:ExpressionBinding Expression="A switch { 0 => 'Idle', 1 or 2 => 'Syncing', > 2 when B => 'Attention', _ => 'Ready' }">
<Binding Path="PhaseCode" />
<Binding Path="HasWarnings" />
</expression:ExpressionBinding>
</TextBlock.Text>
</TextBlock>Concatenate strings with numeric expressions directly without StringFormat multi-binding workarounds:
<TextBlock>
<TextBlock.Text>
<expression:ExpressionBinding Expression="'Progress: ' + round(A * 100) + '% (' + B + '/' + C + ')'">
<Binding Path="Ratio" />
<Binding Path="CompletedCount" />
<Binding Path="TotalCount" />
</expression:ExpressionBinding>
</TextBlock.Text>
</TextBlock>Ordinary operators propagate unset (AvaloniaProperty.UnsetValue). Use a switch pattern to supply a fallback when a dynamic resource or binding is unset or null:
<Border>
<Border.CornerRadius>
<expression:ExpressionBinding Expression="A switch { unset or null => cornerRadius(8), _ => A }">
<DynamicResource ResourceKey="CardCornerRadius" />
</expression:ExpressionBinding>
</Border.CornerRadius>
</Border>Register custom functions on ExpressionRegistry.Default during application startup (function names are case-insensitive):
// 1. Register a delegate (supports closures / captured state)
ExpressionRegistry.Default.RegisterFunction("scale", static (double value, double factor) => value * factor);
// 2. Register all public static overloads of a method name (supports open generics & params)
ExpressionRegistry.Default.RegisterFunction("numericMin", typeof(NumericFunctions), nameof(NumericFunctions.Min));
// 3. Register a specific static MethodInfo (including non-public static methods)
var helperMethod = typeof(InternalHelpers).GetMethod(
nameof(InternalHelpers.Compute),
BindingFlags.Static | BindingFlags.NonPublic)!;
ExpressionRegistry.Default.RegisterFunction("compute", helperMethod);And consume them directly in AXAML:
<Border.Margin>
<expression:ExpressionBinding Expression="thickness(A * 2, 16, B, 16)">
<ReflectionBinding Path="LeftInset" />
<ReflectionBinding Path="RightInset" />
</expression:ExpressionBinding>
</Border.Margin>You can also create an isolated ExpressionRegistry instance and assign it to ExpressionBinding.Registry when a component needs a scoped function set. Adding an overload increments the registry version and invalidates cached call-site rules created from earlier versions.
Every new ExpressionRegistry comes pre-populated with:
| Category | Functions | Supported Types / Signatures |
|---|---|---|
| Numeric | min, max |
int, long, float, double, decimal (2-arg & variadic params) |
clamp, abs, sign |
int, long, float, double, decimal |
|
round, floor, ceil, truncate |
float, double, decimal |
|
pow, log |
float, double |
|
| Conversion | bool |
bool, int, long, float, double, decimal |
| Avalonia Geometry | thickness |
(uniform), (horizontal, vertical), (left, top, right, bottom) |
cornerRadius |
(uniform), (topLeft, topRight, bottomRight, bottomLeft) |
|
size, point, vector |
(double, double) |
See the Language Specification for the complete grammar, operator precedence, conversion rules, and pending specification items.
- Identifiers & Literals:
A–Z, numeric literals, single/double-quoted strings,true,false,null,unset(AvaloniaProperty.UnsetValue). - Operators: Unary
+,-,!,~; arithmetic*,/,%,+,-; shifts<<,>>; comparisons<,<=,>,>=,==,!=; bitwise&,^,|; short-circuit&&,||. - Control Flow: Ternary
condition ? whenTrue : whenFalseandswitchexpressions with constant, relational (<,<=,>,>=), discard (_), andorpatterns plus optionalwhenguards. - Unset & DoNothing: Any
BindingOperations.DoNothinginput short-circuits before evaluation and returnsDoNothing.unsetpropagates across operators, conditional tests, andwhenguards while remaining observable via==andunsetswitch patterns. - Scope: Member access (
a.B), indexer syntax, assignments, and object construction syntax are not part of the language—delegate source path navigation to child Avalonia bindings and expose computations as registered functions.
Expression text
│
▼
Parlot source-generated parser ──► immutable syntax tree
│
▼
fixed LINQ control-flow plan
│
Binding values ───────────────────────┼──► DLR call sites
Function registry ────────────────────┘ │
▼
cached type-specific rules
│
▼
expression result
- When
RuntimeFeature.IsDynamicCodeSupportedisfalse(such as under NativeAOT),ExpressionPlanCompilerautomatically compiles withpreferInterpretation: true. - Boolean conversion uses an explicitly typed
CallSite<T>delegate so its closed signature remains visible to NativeAOT. - Closed delegates and built-in functions work out of the box under NativeAOT; open generic static method registrations cannot be closed dynamically at runtime under NativeAOT (register closed delegates instead).
Building requires .NET SDK 11.0.100 (or a later 11.0.1xx patch). All NuGet dependencies resolve directly from nuget.org via NuGet.config.
dotnet restore ExpressionBinding.Avalonia.slnx --configfile NuGet.config
dotnet build ExpressionBinding.Avalonia.slnx --no-restore -c Release
dotnet test tests/ExpressionBinding.Avalonia.Tests/ExpressionBinding.Avalonia.Tests.csproj --no-build -c ReleaseTo verify NativeAOT compilation and execution locally:
dotnet publish tests/ExpressionBinding.Avalonia.AotSmoke/ExpressionBinding.Avalonia.AotSmoke.csproj -c Release -o artifacts/aot-smoke
./artifacts/aot-smoke/ExpressionBinding.Avalonia.AotSmokeExpressionBinding.Avalonia is distributed under the MIT License.
The source-generated parser contains support code derived from Parlot under the BSD 3-Clause License; see Third-Party Notices.