desktop-mvvm
БесплатноБез исполняемых скриптовНе проверенMVVM for .NET desktop apps (WPF, Avalonia, WinForms, MAUI) with CommunityToolkit.Mvvm 8.4+: [ObservableProperty], [RelayCommand], UI-thread dispatching…
от codewithmukesh★ 858 звёзд на GitHubОб этом скилле
Desktop MVVM (.NET 10, CommunityToolkit.Mvvm)
Core Principles
- View models know nothing about the UI framework — No
Window,MessageBox,Dispatcher, orVisibilityin a view model. That keeps them unit-testable without a UI thread and portable between WPF, Avalonia, and MAUI. - Source generators over hand-written
INotifyPropertyChanged— CommunityToolkit.Mvvm (8.4.x, verified) generates the property, change notification, and command boilerplate at compile time. There's no reflection, so it stays trimming- and AOT-friendly. - Use partial properties, not fields — Since 8.4,
[ObservableProperty]goes onpartialproperties. From 8.4.1 that works on C# 14 with noLangVersion=preview. You get real properties that you can put attributes on and debug, instead of fields with magic names. - Async commands, never
async void—[RelayCommand]on aTask-returning method generates anIAsyncRelayCommand. It disables itself while running, surfaces exceptions, and supports cancellation. - Generic Host is the composition root — DI, configuration, logging, and
IHttpClientFactorywork the same as in ASP.NET Core. Views and view models are resolved from the container, nevernew-ed in code-behind.
Patterns
View Model with Generated Properties and Commands
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
public sealed partial class OrdersViewModel(IOrderService orders, TimeProvider clock) : ObservableObject
{
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
public partial string? CustomerName { get; set; }
[ObservableProperty]
public partial OrderRow? SelectedOrder { get; set; }
public ObservableCollection<OrderRow> Orders { get; } = [];
// Generates LoadCommand (IAsyncRelayCommand) + LoadCancelCommand
[RelayCommand(IncludeCancelCommand = true)]
private async Task LoadAsync(CancellationToken ct)
{
Orders.Clear();
await foreach (var order in orders.StreamAsync(ct))
Orders.Add(order); // continuation resumes on the UI thread
}
[RelayCommand(CanExecute = nameof(CanSave))]
private Task SaveAsync(CancellationToken ct) =>
orders.CreateAsync(CustomerName!, clock.GetUtcNow(), ct);
private bool CanSave() => !string.IsNullOrWhiteSpace(CustomerName);
partial void OnSelectedOrderChanged(OrderRow? value) =>
CustomerName = value?.Customer; // generated hook, no setter boilerplate
}
Why: the class must be partial so the generator can add members. Async is stripped from command names (LoadAsync → LoadCommand). The command is disabled while it runs (unless AllowConcurrentExecutions = true), so double-clicks can't start two loads. Bind a busy indicator to LoadCommand.IsRunning instead of keeping a hand-rolled IsBusy flag.
Generic Host in WPF
Remove StartupUri from App.xaml, then own startup in App.xaml.cs:
public sealed partial class App : Application
{
private readonly IHost host = CreateHost();
private static IHost CreateHost()
{
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings
{
ContentRootPath = AppContext.BaseDirectory // appsettings.json next to the exe, not the cwd
});
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
builder.Services.AddHttpClient<IOrderService, OrderService>();
builder.Services.AddTransient<OrdersViewModel>();
builder.Services.AddSingleton<MainWindow>();
return builder.Build();
}
protected override void OnStartup(StartupEventArgs e)
{
host.Start(); // starts IHostedService background work, if any
host.Services.GetRequiredService<MainWindow>().Show();
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
// Process exit is the one place sync-over-async is acceptable (like Program.cs)
host.StopAsync(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult();
host.Dispose();
base.OnExit(e);
}
}
public sealed partial class MainWindow : Window
{
public MainWindow(OrdersViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
}
Why: one composition root shared with your backend knowledge. Constructor injection into windows keeps code-behind to InitializeComponent + DataContext. Setting the content root to AppContext.BaseDirectory stops a shortcut's "Start in" folder from changing which config loads. Avalonia wiring lives in references/avalonia.md.
UI-Thread Dispatching
await started on the UI thread resumes on the UI thread, so most code needs no dispatching. Dispatch only for callbacks that arrive on background threads (timers, FileSystemWatcher, sockets, message buses).
Установить desktop-mvvm в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл desktop-mvvm?
MVVM for .NET desktop apps (WPF, Avalonia, WinForms, MAUI) with CommunityToolkit.Mvvm 8.4+: [ObservableProperty], [RelayCommand], UI-thread dispatching; Avalonia 12 in references/avalonia.md. Use for "MVVM", "ViewModel", "WPF", "Avalonia", "AXAML", "RelayCommand". Do NOT use for command-line tools (use console-cli) or web APIs (use minimal-api).
Как установить скилл desktop-mvvm?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл desktop-mvvm запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic