Skip to content

About

Runtime-bound, strongly executed expressions for Avalonia bindings

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ExpressionBinding.Avalonia Logo

ExpressionBinding.Avalonia

Runtime-bound, strongly executed expressions for Avalonia bindings

NuGet .NET 8, .NET 10, and .NET 11 Avalonia 12+ MIT License

English | 简体中文


Introduction

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.

Features

  • Zero boilerplate XAML expressions: Combine any mix of CompiledBinding, ReflectionBinding, DynamicResource, or constant values using positional arguments A through Z.
  • Rich C#-inspired syntax: Supports arithmetic, bitwise, shift, comparison, logical short-circuiting (&& / ||), conditional (?:), and switch expressions with relational/discard/or patterns and when guards.
  • Avalonia-native binding semantics: Properly handles BindingOperations.DoNothing and AvaloniaProperty.UnsetValue (unset literal & sentinel propagation).
  • Extensible function registries: Register closed delegates, static method groups, or MethodInfo entries (including params 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, and net11.0 against Avalonia 12.0.0+.

Getting Started

1. Install the NuGet package

dotnet add package ExpressionBinding.Avalonia

2. Use ExpressionBinding in AXAML

Declare 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 A through Z (case-sensitive) map in order to child items in Arguments.
  • Child items may be any Avalonia BindingBase or a literal/object value (non-binding objects are automatically wrapped in a one-way CompiledBinding).
  • ExpressionBinding always produces a one-way MultiBinding.

Common Scenarios

Tip

Inside XML attribute strings (Expression="..."), use single quotes ('...') for string literals and XML-escape < / & as &lt; / &amp; (for example &lt; 520 and &amp;&amp;).

1. Theme-Token Layout & Responsive Sizing

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>

2. Multi-Condition State (IsEnabled, IsVisible, Opacity)

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 &amp;&amp; B &gt; 0 &amp;&amp; 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>

3. Responsive Breakpoints & Status Labels (switch)

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 { &lt; 520 => 1, &lt; 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', &gt; 2 when B => 'Attention', _ => 'Ready' }">
      <Binding Path="PhaseCode" />
      <Binding Path="HasWarnings" />
    </expression:ExpressionBinding>
  </TextBlock.Text>
</TextBlock>

4. Inline String Formatting

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>

5. Safe Fallback for unset and null

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>

Custom Functions & Registries

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.

Built-in Functions

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)

Expression Language Summary

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 : whenFalse and switch expressions with constant, relational (<, <=, >, >=), discard (_), and or patterns plus optional when guards.
  • Unset & DoNothing: Any BindingOperations.DoNothing input short-circuits before evaluation and returns DoNothing. unset propagates across operators, conditional tests, and when guards while remaining observable via == and unset switch 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.

Execution Model & NativeAOT

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.IsDynamicCodeSupported is false (such as under NativeAOT), ExpressionPlanCompiler automatically compiles with preferInterpretation: 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).

Build & Test

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 Release

To 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.AotSmoke

License

ExpressionBinding.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.

About

Runtime-bound, strongly executed expressions for Avalonia bindings

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages