Index of every page on this site: llms.txt
All skills
github avatar

/mvvm-toolkit

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

CommunityToolkit.Mvvm (the MVVM Toolkit) core: source generators ([ObservableProperty], [RelayCommand], [NotifyPropertyChangedFor], [NotifyCanExecuteChangedFor], [NotifyDataErrorInfo]), base classes (ObservableObject / ObservableValidator / ObservableRecipient), commands (RelayCommand / AsyncRelayCommand), and validation. Companion skills: mvvm-toolkit-messenger for pub/sub, mvvm-toolkit-di for Microsoft.Extensions.DependencyInjection wiring. Works across WPF, WinUI 3, MAUI, Uno, and Avalonia.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/mvvm-toolkit

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesrelaycommand-cookbook.md

≈1.7k tokens on demand. Your agent reads this file only when SKILL.md points to it.

RelayCommand cookbook

Recipes for RelayCommand / AsyncRelayCommand and the [RelayCommand] generator. Defaults to the generator-attribute style; manual constructor patterns are listed at the bottom for advanced cases.


Sync command

[RelayCommand]
private void IncrementCounter() => Counter++;
<Button Command="{x:Bind ViewModel.IncrementCounterCommand}" Content="+1"/>

Sync command with parameter

[RelayCommand]
private void RemoveItem(Item item) => Items.Remove(item);
<Button Command="{x:Bind ViewModel.RemoveItemCommand}"
        CommandParameter="{x:Bind Item}" Content="Remove"/>

The generator picks IRelayCommand<Item> based on the parameter type.

Sync command with CanExecute

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
private string? text;

[RelayCommand(CanExecute = nameof(CanSubmit))]
private void Submit() => service.Submit(Text!);

private bool CanSubmit() => !string.IsNullOrWhiteSpace(Text);

[NotifyCanExecuteChangedFor] raises CanExecuteChanged automatically whenever Text changes — without it, the button stays disabled even after the user types.


Async command

[RelayCommand]
private async Task LoadAsync()
{
    Items.Clear();
    foreach (var item in await service.GetItemsAsync())
        Items.Add(item);
}

Bind the UI to LoadCommand.IsRunning to show a spinner:

<ProgressRing IsActive="{x:Bind ViewModel.LoadCommand.IsRunning, Mode=OneWay}"/>

Async command with cancellation

[RelayCommand(IncludeCancelCommand = true)]
private async Task DownloadAsync(CancellationToken token)
{
    try
    {
        await using var stream = await http.GetStreamAsync(url, token);
        // ...
    }
    catch (OperationCanceledException)
    {
        // Expected — user cancelled.
    }
}
<Button Command="{x:Bind ViewModel.DownloadCommand}" Content="Download"/>
<Button Command="{x:Bind ViewModel.DownloadCancelCommand}" Content="Cancel"/>

DownloadCancelCommand.CanExecute is automatically wired to DownloadCommand.IsRunning.

Async command with concurrency

[RelayCommand(AllowConcurrentExecutions = true)]
private async Task PingAsync(string host)
{
    await pingService.PingAsync(host);
}

Default (AllowConcurrentExecutions = false) reports the command as disabled while a previous execution is pending. Set to true for fire-and-forget patterns where overlapping invocations are safe.

Async command that surfaces errors to UI

[RelayCommand(FlowExceptionsToTaskScheduler = true)]
private async Task SyncAsync(CancellationToken token)
{
    await syncService.SyncAsync(token);
}
<TextBlock Text="{x:Bind ViewModel.SyncCommand.ExecutionTask.Exception, Mode=OneWay}"/>

Without FlowExceptionsToTaskScheduler = true, an uncaught exception in SyncAsync will crash the app (mirroring sync commands). With it, the exception is surfaced through ExecutionTask and bubbles to TaskScheduler.UnobservedTaskException.

Showing async command status

<StackPanel>
    <ProgressRing IsActive="{x:Bind ViewModel.SyncCommand.IsRunning, Mode=OneWay}"/>
    <TextBlock Text="{x:Bind ViewModel.SyncCommand.ExecutionTask.Status, Mode=OneWay}"/>
</StackPanel>

Useful properties on IAsyncRelayCommand:

Property Type Purpose
ExecutionTask Task? The currently running (or last completed) task
IsRunning bool true while a task is in flight
CanBeCanceled bool true if the wrapped method takes a CancellationToken
IsCancellationRequested bool true after Cancel() was called for the in-flight task

Methods:

Method Purpose
Cancel() Signals the active CancellationToken
NotifyCanExecuteChanged() Re-evaluates CanExecute and raises CanExecuteChanged

Forwarding attributes to the generated command property

[RelayCommand]
[property: JsonIgnore]
[property: Description("Saves the current document")]
private Task SaveAsync() => repo.SaveAsync(Text!);

The generator emits SaveCommand with [JsonIgnore] and [Description] applied — useful when the VM is serialized.


Manual RelayCommand / AsyncRelayCommand

Reach for the manual constructors when you need:

  • A command composed from multiple methods or dynamically rebuilt
  • A CanExecute predicate built from external observables
  • An ICommand instance held in a field (rare; the generator's lazy property is enough for almost every case)
public sealed class CounterViewModel : ObservableObject
{
    public CounterViewModel()
    {
        IncrementCommand = new RelayCommand(() => Counter++);
        DecrementCommand = new RelayCommand(() => Counter--, () => Counter > 0);
    }

    [ObservableProperty]
    private int counter;

    public IRelayCommand IncrementCommand { get; }
    public IRelayCommand DecrementCommand { get; }
}
public sealed class DownloadViewModel : ObservableObject
{
    public DownloadViewModel()
    {
        DownloadCommand = new AsyncRelayCommand(DownloadAsync, () => CanDownload);
    }

    [ObservableProperty]
    private bool canDownload = true;

    public IAsyncRelayCommand DownloadCommand { get; }

    private async Task DownloadAsync()
    {
        CanDownload = false;
        try { await http.DownloadAsync(); }
        finally { CanDownload = true; }
    }
}

Trigger CanExecute re-evaluation manually with SomeCommand.NotifyCanExecuteChanged().


Task.WhenAll from a single command

[RelayCommand]
private async Task SyncAllAsync(CancellationToken token)
{
    var tasks = providers.Select(p => p.SyncAsync(token));
    await Task.WhenAll(tasks);
}

If you want individual progress tracking per provider, expose one command per provider instead.


Common mistakes

  1. async void instead of async Task. The generator only wraps Task-returning methods as IAsyncRelayCommand. async void becomes a sync RelayCommand and exceptions are unobserved.
  2. Forgetting [NotifyCanExecuteChangedFor]. The button stays disabled even though CanX() would now return true.
  3. Calling Cancel() on a non-cancellable command. Only commands whose wrapped method accepts a CancellationToken honor Cancel().
  4. Catching OperationCanceledException and rethrowing as a different type. Loses cancellation semantics; ExecutionTask.IsCanceled will be false. Let OperationCanceledException propagate (or return).
  5. Awaiting IAsyncRelayCommand.ExecuteAsync() from inside another [RelayCommand]. Prefer calling the underlying method directly to avoid double-wrapping the cancellation/concurrency semantics.

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides documentation and code templates for using the .NET CommunityToolkit.Mvvm library. It covers MVVM patterns, source generators, and validation. All code snippets follow standard development practices, and all external links point to trusted official Microsoft or Community Toolkit resources. No security issues were detected.

  • Socket2mo

    1 alert: gptAnomaly

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 7 months ago
  • csharp
  • mvvm
  • observable-property
  • relay-command
  • wpf
  • winui
  • maui
  • avalonia
  • validation
  • source-generators

README badge

README badge for github/awesome-copilot/mvvm-toolkit

Provides source generators and base classes for the MVVM Toolkit library: `[ObservableProperty]` for properties, `[RelayCommand]` for commands, `ObservableObject` / `ObservableValidator` / `ObservableRecipient` base classes, and validation via `INotifyDataErrorInfo`. Targets WPF, WinUI 3, MAUI, Uno, and Avalonia apps using CommunityToolkit.Mvvm 8.x.

Generated from the current SKILL.md.

Does this work with WPF, WinUI, MAUI, and Avalonia?
Yes. The MVVM Toolkit supports WPF, WinUI 3, MAUI, Uno, and Avalonia across netstandard2.0, netstandard2.1, and net6.0+.
Do I need to declare classes as partial?
Yes. Every class using [ObservableProperty] or [RelayCommand], and every enclosing type if nested, must be declared partial. Omitting it triggers compiler error MVVMTK0008 or MVVMTK0042.
How do I wire up dependent properties and commands that need to update when an observable field changes?
Use [NotifyPropertyChangedFor(nameof(...))] to propagate PropertyChanged to dependent properties, and [NotifyCanExecuteChangedFor(nameof(...))] to notify commands that their CanExecute state may have changed.
What do I use for form validation?
Inherit from ObservableValidator instead of ObservableObject, apply [NotifyDataErrorInfo] and validation attributes like [Required] and [EmailAddress] to observable fields, then call ValidateAllProperties() and check HasErrors.
Are there companion skills for messaging and dependency injection?
Yes. Load mvvm-toolkit-messenger for IMessenger pub/sub patterns, and mvvm-toolkit-di for Microsoft.Extensions.DependencyInjection integration.

Generated from the current SKILL.md. These answers refresh after source changes.