3.2. Getting Started with VMx — C#¶
This tutorial walks you through building viewmodels with the VMx C# library.
You will build a ComponentVM<UserModel>, a RelayCommand with a reactive
trigger, and a tab composite with tab selection — all in a console or
unit-test project. The code blocks form one program in page order. Option A and
Option B of section 3.2.2 are alternatives, and the later blocks use the hub and
dispatcher of Option A.
For the contracts behind each type, see the component family, command families, and composite family.
3.2.1. Install¶
Add VMx as described in Installation. The NuGet package
is not published, so the C# section of that page references the VMx project
from a checkout. This tutorial needs only the core VMx project; section 3.2.2.2 adds
the optional dependency-injection project.
3.2.2. Wire Up IMessageHub And IDispatcher¶
The viewmodels in this tutorial need two services: a hub that carries messages between viewmodels and a dispatcher that knows about your UI thread.
3.2.2.1. Option A — Manual Construction (Console / Tests)¶
using VMx.Services;
// Both foreground and background = immediate (deterministic for console / tests).
// Mirrors RxDispatcher.immediate() in Python and TypeScript.
IDispatcher dispatcher = RxDispatcher.Immediate();
IMessageHub hub = new MessageHub();
3.2.2.2. Option B — Dependency Injection (VMx.Extensions.DependencyInjection)¶
Add the optional DI project:
<ProjectReference Include="../VMx/langs/csharp/src/VMx.Extensions.DependencyInjection/VMx.Extensions.DependencyInjection.csproj" />
The DI package references only the service-collection abstractions. A host
such as WPF, MAUI, or ASP.NET Core already supplies the container. A console
app that calls BuildServiceProvider() itself also needs the
Microsoft.Extensions.DependencyInjection package.
The default AddVMx() dispatcher binds to the SynchronizationContext that
is current when AddVMx() runs, so call it on the UI thread of a WPF,
WinForms, MAUI, or Avalonia app. If there is no context at that time, the
first resolution of IDispatcher tries the context of the resolving thread.
ASP.NET Core and console hosts have no SynchronizationContext, so the default
throws InvalidOperationException there; supply a dispatcher factory instead,
for example RxDispatcher.Immediate().
Register VMx in your host startup:
using Microsoft.Extensions.DependencyInjection;
using VMx.Extensions.DependencyInjection;
using VMx.Services;
var services = new ServiceCollection();
// Host without a SynchronizationContext (console, tests, ASP.NET Core): supply
// a dispatcher factory.
services.AddVMx(opts => opts.UseDispatcher(_ => RxDispatcher.Immediate()));
// UI host instead: IMessageHub → singleton MessageHub,
// IDispatcher → singleton RxDispatcher bound to SynchronizationContext.Current
// services.AddVMx();
var provider = services.BuildServiceProvider();
var diHub = provider.GetRequiredService<IMessageHub>();
var diDispatcher = provider.GetRequiredService<IDispatcher>();
The rest of this tutorial uses the hub and dispatcher of Option A. An
application that uses the container passes diHub and diDispatcher to its
viewmodels instead.
3.2.3. Build A ComponentVM<UserModel>¶
ComponentVM<M> is the primary leaf viewmodel. It holds a typed model,
fires IPropertyChangedMessage on the hub when the model changes, and
participates in the lifecycle: four reversible states (Destructed,
Constructing, Constructed, Destructing) and the terminal Disposed state.
using System.Reactive.Linq;
using VMx.Components;
using VMx.Messages;
using VMx.Services;
// Build the viewmodel — builder is immutable; every setter returns a new instance.
ComponentVM<UserModel> userVM =
ComponentVM<UserModel>.Builder()
.Name("user-card")
.Model(new UserModel("Alice", "alice@example.com"))
.Services(hub, dispatcher)
// Optional: derive a display hint from the model.
.ModeledHinter(m => m.Name)
// Optional: callback when Model is set to a new value.
.OnModelChanged(m => Console.WriteLine($"Model updated → {m.Name}"))
.OnConstruct(() => Console.WriteLine("user-card constructed"))
.OnDestruct(() => Console.WriteLine("user-card destructed"))
.Build();
// Subscribe to PropertyChangedMessage BEFORE constructing so you don't miss it.
hub.Messages
.OfType<IPropertyChangedMessage<IComponentVM>>()
.Where(msg => msg.Sender == userVM)
.Subscribe(msg =>
Console.WriteLine($"Property '{msg.PropertyName}' changed on {msg.Sender.Name}"));
// Construct transitions the VM: Destructed → Constructing → Constructed.
// The VM publishes ConstructionStatusChangedMessage on the hub for each
// transition and fires its OnConstruct callback when entering Constructing.
userVM.Construct();
// Update the model — triggers OnModelChanged and publishes PropertyChangedMessage.
userVM.Model = new UserModel("Alice Smith", "asmith@example.com");
Console.WriteLine(userVM.ModeledHint); // "Alice Smith" (ModeledHinter result)
// A simple domain model — use your own real types here. In a file with
// top-level statements, type declarations come after the statements.
public record UserModel(string Name, string Email);
See the component family for the full
IComponentVM<M>contract and Services, Messages & Dispatching for the message schema.
3.2.4. Build A RelayCommand¶
RelayCommand wraps a nullable Action, an optional Func<bool> predicate,
and a set of IObservable<Unit> triggers that re-evaluate CanExecute.
using System.Reactive;
using System.Reactive.Subjects;
using System.Windows.Input;
using VMx.Commands;
using VMx.Services;
// A subject you fire whenever the predicate outcome may have changed.
var canSaveTrigger = new Subject<Unit>();
bool isDirty = false;
ICommand saveCommand =
RelayCommand.Builder()
.Task(() =>
{
Console.WriteLine("Saving…");
isDirty = false;
canSaveTrigger.OnNext(Unit.Default); // re-evaluate CanExecute
})
.Predicate(() => isDirty)
.Triggers(canSaveTrigger)
.Build();
// CanExecute is false until isDirty is true.
Console.WriteLine(saveCommand.CanExecute(null)); // False
isDirty = true;
canSaveTrigger.OnNext(Unit.Default); // fires CanExecuteChanged
Console.WriteLine(saveCommand.CanExecute(null)); // True
saveCommand.Execute(null); // prints "Saving…"
Console.WriteLine(saveCommand.CanExecute(null)); // False again
// Dispose to unsubscribe all trigger subscriptions.
((IDisposable)saveCommand).Dispose();
See command families for the full command contract, including the "predicate-false gates Execute" rule (CMD-007).
3.2.5. Build A Tab Composite¶
CompositeVM<VM> owns an ordered child collection and a Current selection.
Children are built ahead of time and handed in via a factory; the factory runs
lazily on the first Construct.
using System.Reactive.Linq;
using VMx.Components;
using VMx.Composites;
using VMx.Services;
// Build two tab children. They share the same hub and dispatcher.
ComponentVM<TabModel> tab1 =
ComponentVM<TabModel>.Builder()
.Name("home-tab")
.Model(new TabModel("Home"))
.Services(hub, dispatcher)
.Build();
ComponentVM<TabModel> tab2 =
ComponentVM<TabModel>.Builder()
.Name("settings-tab")
.Model(new TabModel("Settings"))
.Services(hub, dispatcher)
.Build();
// Build the composite. The children factory is evaluated on Construct.
CompositeVM<ComponentVM<TabModel>> tabs =
CompositeVM<ComponentVM<TabModel>>.Builder()
.Name("tab-bar")
.Services(hub, dispatcher)
.Children(() => [tab1, tab2])
.OnConstruct(() => Console.WriteLine("tab-bar constructing"))
.Build();
// Watch for Current changes on the hub.
hub.WhenPropertyChanged(tabs, nameof(tabs.Current))
.Subscribe(_ =>
{
Console.WriteLine($"Selected tab: {tabs.Current?.Model.Title ?? "(none)"}");
});
// The hook runs while the composite is Constructing. Each child then
// constructs, and the composite becomes Constructed after the last child.
tabs.Construct();
// Select a tab — publishes PropertyChangedMessage for Current, sets child.IsCurrent.
tabs.Current = tab2; // prints "Selected tab: Settings"
tabs.Current = tab1; // prints "Selected tab: Home"
// A tab viewmodel — a ComponentVM wrapping a tab model.
public record TabModel(string Title);
See the composite family for the full
ICompositeVM<VM>contract, including theIList<VM>/INotifyCollectionChangedsemantics.
3.2.6. Lifecycle And Cleanup¶
The VMs in this tutorial have five lifecycle states. Four of them form a reversible cycle, Destructed → Constructing → Constructed → Destructing → Destructed. The fifth state, Disposed, is terminal.
// States are exposed via IComponentVM.Status (a ConstructionStatus enum).
Console.WriteLine(userVM.Status); // Constructed (after Construct())
// Reconstruct is Destruct + Construct in one call. It is only valid from
// Constructed (CanReconstruct is true iff Status == Constructed); it
// round-trips through Destructed and back to Constructed.
userVM.Reconstruct();
Console.WriteLine(userVM.Status); // Constructed
// Destruct transitions back to Destructed and runs OnDestruct.
userVM.Destruct();
Console.WriteLine(userVM.Status); // Destructed
// Dispose is terminal and idempotent. Calling Construct() or Destruct() on a
// disposed VM raises StatusTransitionException.
userVM.Dispose();
Console.WriteLine(userVM.Status); // Disposed
// CompositeVM.Dispose() disposes children then itself.
tabs.Dispose();
Dispose the hub last, after every viewmodel that uses it. MessageHub.Dispose()
completes the underlying Rx subject. The threading examples below still use the
hub, so the full shutdown sequence appears at the end of section 3.2.7.
The C#-specific ConstructAsync(), DestructAsync(), and
ReconstructAsync() methods complete after terminal lifecycle publication.
Their failure and disposal-race rules are in
Lifecycle & Messaging.
See Lifecycle & Messaging for the transition table, the error of a refused operation, and the callback ordering.
3.2.7. Threading¶
IDispatcher pairs two Rx schedulers:
| Scheduler | Typical mapping |
|---|---|
dispatcher.Foreground |
UI thread (SynchronizationContext, Dispatcher) |
dispatcher.Background |
Task pool / background threads |
All hub observations delivered on Foreground are safe to bind directly to UI
controls. Use ObserveOn to marshal:
using System.Reactive.Linq;
// Stub for your UI code: replace it with the label update.
void UpdateLabel(object msg) { }
hub.Messages
.OfType<IPropertyChangedMessage<IComponentVM>>()
.ObserveOn(dispatcher.Foreground) // marshal to UI thread
.Subscribe(msg => UpdateLabel(msg)); // safe to touch UI here
The next example loads data in the background before Construct. It builds a
new viewmodel because section 3.2.6 disposed userVM.
using System.Reactive.Linq;
using VMx.Components;
ComponentVM<UserModel> profileVM =
ComponentVM<UserModel>.Builder()
.Name("profile")
.Model(new UserModel("", ""))
.Services(hub, dispatcher)
.Build();
// Stub for your data access: replace it with a real load.
UserModel LoadFromDatabase() => new UserModel("Loaded", "loaded@example.com");
Observable
.Start(() => LoadFromDatabase(), dispatcher.Background)
.ObserveOn(dispatcher.Foreground)
.Subscribe(data =>
{
profileVM.Model = data;
profileVM.Construct();
});
At shutdown, dispose the viewmodels first and the hub last:
profileVM.Dispose();
((IDisposable)hub).Dispose();
See Services, Messages & Dispatching for the foreground rules for property and collection changes.
3.2.8. Where To Go Next¶
| Resource | Documentation page |
|---|---|
| Specification status | Specification & Conformance |
| Lifecycle contract | Lifecycle & Messaging |
| Messages & threading | Services, Messages & Dispatching |
| Commands | Command Families |
| Component contract | Component Family |
| Composite contract | Composite Family |
| Builders & tree | Builders, Collections & Tree Utilities |
| Architecture | Architecture Map |
| C# status | C# Flavor |
| Examples | Smaller Examples |