9.3. WPF Integration¶
Wire a ComponentVM<M> to a WPF view through INotifyPropertyChanged and
RelayCommand. This page is the shared home of the XAML adapter that the
Avalonia and MAUI recipes also use. WPF is Windows-only; for
cross-platform XAML, see avalonia.md.
9.3.1. Reactivity Primitive¶
WPF, Avalonia, and MAUI bindings observe INotifyPropertyChanged.PropertyChanged
and ICommand. ComponentVMBase implements INotifyPropertyChanged. A setter
such as Model publishes a PropertyChangedMessage to the hub and then raises
PropertyChanged. A lifecycle transition publishes a
ConstructionStatusChangedMessage to the hub and then raises PropertyChanged
for both Status and IsConstructed. Status is computed, so the hub never
carries a PropertyChangedMessage for it.
9.3.2. Mapping¶
This mapping applies to all three XAML hosts. The Avalonia and MAUI pages add only their host-specific rows.
| XAML host | VMx |
|---|---|
INotifyPropertyChanged |
ComponentVMBase.PropertyChanged (implemented by every VM) |
ICommand |
RelayCommand / RelayCommand<T> (implements ICommand) |
INotifyCollectionChanged |
ServicedObservableCollection<T> or wrap ObservableList<T> |
WPF Dispatcher thread |
SynchronizationContextScheduler created on the UI thread (host) |
9.3.3. XAML Adapter¶
WPF, Avalonia, and MAUI use this adapter unchanged. The adapter is
langs/csharp/tests/VMx.Tests/Integration/BindableVm.cs. XamlRecipeTests.cs
in the same folder executes it on test schedulers. CI also runs it against real
WPF bindings on a Dispatcher thread (examples/csharp/wpf/RecipeHostCheck, which
targets net8.0-windows: WPF on .NET 8).
using System.ComponentModel;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using VMx.Commands;
using VMx.Components;
using VMx.Lifecycle;
/// <summary>
/// Binds a borrowed <see cref="ComponentVM{M}"/> to XAML. The VM's creator
/// constructs and disposes it; this adapter only observes it.
/// </summary>
public sealed class BindableVm<M> : INotifyPropertyChanged, IDisposable
{
private readonly ComponentVM<M> _vm;
private readonly IDisposable _subscription;
/// <param name="vm">The VM to show.</param>
/// <param name="host">
/// The UI thread's scheduler, for example a
/// <see cref="SynchronizationContextScheduler"/> created on the UI thread.
/// </param>
public BindableVm(ComponentVM<M> vm, IScheduler host)
{
_vm = vm;
// ComponentVM<M> implements INotifyPropertyChanged: it raises Model on
// assignment, and Status and IsConstructed on every lifecycle
// transition, on the thread that made the change. Forward each
// notification on the UI thread. Hub messages are not forwarded: the
// hub carries status changes as ConstructionStatusChangedMessage, not
// as a Status PropertyChanged, and its Model message would notify a
// second time.
_subscription = Observable
.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
handler => vm.PropertyChanged += handler,
handler => vm.PropertyChanged -= handler)
.ObserveOn(host)
.Subscribe(change => PropertyChanged?.Invoke(this, change.EventArgs));
}
/// <summary>The VM's model; assigning it replaces the VM's model.</summary>
public M Model
{
get => _vm.Model;
set => _vm.Model = value;
}
/// <summary>The VM's name.</summary>
public string Name => _vm.Name;
/// <summary>The VM's lifecycle status.</summary>
public ConstructionStatus Status => _vm.Status;
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>Stops observing the VM without changing its lifecycle.</summary>
public void Dispose() => _subscription.Dispose();
}
/// <summary>
/// The data context for one note: the adapter that shows it and the command
/// that the Save button runs. Both are borrowed, as the adapter is.
/// </summary>
public sealed class BindableScreen<M>
{
/// <param name="note">The adapter that shows the note.</param>
/// <param name="save">The command that the Save button runs.</param>
public BindableScreen(BindableVm<M> note, RelayCommand save)
{
Note = note;
SaveCommand = save;
}
/// <summary>The adapter that shows the note.</summary>
public BindableVm<M> Note { get; }
/// <summary>The command that the Save button runs.</summary>
public RelayCommand SaveCommand { get; }
}
Create the adapter on the UI thread, where WPF installs its
DispatcherSynchronizationContext:
var adapter = new BindableVm<Note>(
vm, new SynchronizationContextScheduler(SynchronizationContext.Current!));
Wrap the adapter and the domain's RelayCommand in a BindableScreen<Note>,
and set it as the data context: new BindableScreen<Note>(adapter, save). Then
in XAML: <TextBlock Text="{Binding Note.Model.Title}"/>,
<TextBlock Text="{Binding Note.Status}"/>, and
<Button Command="{Binding SaveCommand}"/>.
The four adapter rules apply on every XAML host:
- One notification path. Forward
PropertyChangedonly. Forwarding the hub'sPropertyChangedMessageas well notifiesModeltwice, and the hub never carriesStatus. - Current values at once.
Model,Name, andStatusread through to the VM, so a binding shows the VM's current values as soon as it attaches. - UI thread only. The VM raises
PropertyChangedon the thread that made the change, such as a worker or a background construct. The adapter re-raises each notification throughhost, so bound state is only touched on the UI thread. The dispatcher'sForegroundscheduler decides where VMx completes lifecycle work; it does not move your subscriptions. - Borrowed lifetime.
Dispose()detaches the adapter and nothing else. The code that created the VM constructs and disposes it.
9.3.4. Fuller Example¶
examples/csharp/wpf/TodoApp/ — a
working WPF Todo app demonstrating RelayCommand + IMessageHub with
per-item ComponentVM<TodoItem> children in an ObservableCollection.
Its TodoItemVM maps the hub's Model message to its projected Title and
Done properties; it shows no lifecycle status.