9.2. Avalonia Integration¶
Wire a ComponentVM<M> to an Avalonia 12 view. Avalonia targets desktop
(Windows, macOS, Linux), mobile, and browser. VMx tests exercise Avalonia only
on its headless platform; the mobile and browser targets are framework
capabilities that VMx tests do not exercise.
9.2.1. Reactivity Primitive¶
Avalonia binds through INotifyPropertyChanged and ICommand, as WPF does.
The shared rules are in WPF: Reactivity primitive.
Avalonia marshals work to the UI thread through Dispatcher.UIThread. On that
thread, SynchronizationContext.Current is an AvaloniaSynchronizationContext
that posts to it.
9.2.2. Mapping¶
The shared XAML mapping applies. Avalonia adds these rows:
| Avalonia | VMx |
|---|---|
AvaloniaList<T> / ObservableCollection |
ServicedObservableCollection<T> or wrap ObservableList<T> |
Dispatcher.UIThread |
SynchronizationContextScheduler created on the UI thread (host) |
9.2.3. Adapter Skeleton¶
Avalonia uses the XAML adapter BindableVm<M>
unchanged, with the same four rules. The Avalonia showcase tests
(NotesShowcase.Tests/Views/AvaloniaRecipeTests.cs) run it against real
Avalonia bindings on Avalonia's headless UI thread.
Create the adapter on Avalonia's UI thread, for example in a view's
constructor. There SynchronizationContext.Current posts to
Dispatcher.UIThread, so no extra scheduler package is needed. The checked code
below runs under the Avalonia.Headless.XUnit 12.1.6 pin of NotesShowcase.Tests:
var adapter = new BindableVm<Note>(
vm, new SynchronizationContextScheduler(SynchronizationContext.Current!));
Then, with new BindableScreen<Note>(adapter, save) as the data context (see the
XAML adapter), bind {Binding Note.Model.Title},
{Binding Note.Status}, and <Button Command="{Binding SaveCommand}"/>. For lists, bind ItemsSource to a
ServicedObservableCollection<T>, or to a wrapper of an ObservableList<T>. The
control then updates from the collection's INotifyCollectionChanged events, so
no hub message is needed.
9.2.4. Fuller Example¶
examples/csharp/avalonia/NotesShowcase/ —
the Notes-Showcase Avalonia flagship: end-to-end WorkspaceVM,
AggregateVM6, ConfirmationDecoratorCommand, and ThemeVM.