| name | wpf-mvvm |
| description | Build and maintain WPF MVVM patterns using CommunityToolkit.Mvvm for a .NET 8 widget-host app. Use when creating ViewModels, commands, observable state, validation, view bindings, and viewmodel-first navigation behaviors. Avoid Prism and heavy region managers; keep ViewModels testable and UI-agnostic. |
Wpf Mvvm
Overview
Apply MVVM conventions with CommunityToolkit.Mvvm, ensuring view models are UI-agnostic and ready for the widget shell architecture.
Constraints
- Target .NET 8
- CommunityToolkit.Mvvm
- ViewModel-first navigation (custom service)
- No Prism, no heavy region manager
Core conventions
ViewModel base
- Use
ObservableObject(orObservableRecipientif messaging is required). - Keep view models free of
Window,UserControl, orDependencyObjectreferences.
Commands
- Use
[RelayCommand]for commands. - Prefer async commands for IO or long-running work.
- Use
CanExecuteorCanExecutebacking fields for stateful enable/disable.
State and updates
- Use
[ObservableProperty]for state. - Keep state immutable when practical; update via methods.
- Avoid direct access to
Application.Currentinside view models.
Validation
- Use
ObservableValidatorfor data validation. - Prefer
INotifyDataErrorInfovia toolkit attributes.
Typical workflow
- Create or update view model using toolkit attributes.
- Add command handlers and validation rules.
- Bind view to view model with XAML.
- Add DataTemplate mapping for viewmodel-first navigation.
- Write tests for business logic and command behavior.
Example ViewModel
public partial class WidgetViewModel : ObservableObject
{
[ObservableProperty]
private string _title = "Widget";
[RelayCommand]
private void Refresh()
{
// Fetch or recompute widget state.
}
}
Binding guidance
- Bind directly to VM properties with
Mode=TwoWayonly when needed. - Use
UpdateSourceTrigger=PropertyChangedfor live edits. - Keep converters minimal; prefer derived properties in the VM.
References
references/viewmodel-patterns.mdfor structure patterns.references/commands-and-async.mdfor command and async guidance.references/validation.mdfor validation recipes.