diff --git a/shared/rules/wpf/index.md b/shared/rules/wpf/index.md index f8763f3..0e18066 100644 --- a/shared/rules/wpf/index.md +++ b/shared/rules/wpf/index.md @@ -10,3 +10,4 @@ For WPF, XAML, or MVVM work, open only the focused topic rules relevant to the c | Resources and lifecycle | `references/resources-and-lifecycle.md` | `rules-wpf-resources-and-lifecycle` | | Security, errors, logging, and validation | `references/security-and-errors.md` | `rules-wpf-security-and-errors` | | Architecture, dependency injection, testing, and performance | `references/architecture-and-quality.md` | `rules-wpf-architecture-and-quality` | +| Accessibility, DPI scaling, and theming | `references/accessibility-and-theming.md` | `rules-wpf-accessibility-and-theming` | diff --git a/shared/rules/wpf/references/accessibility-and-theming.md b/shared/rules/wpf/references/accessibility-and-theming.md new file mode 100644 index 0000000..18f48e4 --- /dev/null +++ b/shared/rules/wpf/references/accessibility-and-theming.md @@ -0,0 +1,23 @@ +# WPF Accessibility, Scaling, and Theming + +Apply these rules when building or changing WPF views, controls, styles, or themes. Load the UI/UX rules for general interface design; Windows conventions, not macOS ones, decide navigation, menus, and settings. + +## Accessibility + +* Give every interactive element without visible text an accessible name with `AutomationProperties.Name`, and add `AutomationProperties.HelpText` where the purpose is not obvious. Keep names in sync with the visible label or state. +* Make every action reachable by keyboard: logical tab order, `AccessText` or access keys for important commands, and `IsDefault` and `IsCancel` on dialog buttons. Use `KeyboardNavigation` settings deliberately inside lists, toolbars, and custom containers. +* Keep focus visible. Do not remove `FocusVisualStyle` without an equal replacement, and move focus deliberately when dialogs open and close. +* Support high contrast: use `SystemColors` and theme resources instead of hard-coded brushes, and never convey state by color alone. +* Give custom controls an `AutomationPeer` that exposes their role, name, and state, and check them with Narrator and an accessibility inspector. + +## Scaling + +* Lay out in device-independent units with `Auto` and star sizing; never assume 96 DPI or a fixed screen size. +* Use vector icons or multi-resolution image assets so the UI stays sharp at every scale factor, and test at 100, 150, and 200 percent and when moving windows between monitors with different scaling. +* For .NET Framework apps, confirm the app is configured for per-monitor DPI awareness before relying on crisp rendering across monitors. + +## Theming + +* On .NET 9 and later, prefer the built-in Fluent theme for new apps and redesigns: set `ThemeMode="System"` on the `Application` (or a `Window`) to follow the Windows light and dark setting, or `Light` or `Dark` where the product requires it. Do not switch an existing app's theme as a side effect of another task. +* Define colors and brushes as theme-aware resources so light, dark, and high-contrast modes all work, and test each of them. +* Follow Windows conventions for window chrome, menus, dialogs, and settings, and keep text in resources so it can be localized. diff --git a/shared/rules/wpf/references/architecture-and-quality.md b/shared/rules/wpf/references/architecture-and-quality.md index f899813..c0378af 100644 --- a/shared/rules/wpf/references/architecture-and-quality.md +++ b/shared/rules/wpf/references/architecture-and-quality.md @@ -1,77 +1,30 @@ # WPF Architecture, Dependency Injection, Testing, and Performance -Apply these rules when structuring a WPF application, wiring dependency injection, testing view models, or optimizing performance. Load the C# rules for language-level guidance. +Apply these rules when structuring a WPF application, wiring dependency injection, testing view models, or optimizing performance. The C# rules and the shared refactoring rule cover general structure, testing, and code quality; this file adds WPF specifics. ## Architecture -* Use the C# version the project targets (see the C# coding-style rule; .NET Framework 4.x WPF apps default to C# 7.3). Prefer MVVM for non-trivial views and keep code-behind limited to view-specific behavior. -* Keep UI, application, and domain logic separate. Avoid business logic in views and direct service access from controls. -* Keep dependencies explicit and testable; prefer composition over inheritance and avoid unnecessary abstractions or framework wrappers. -* Avoid direct database access from views or ViewModels. -* Avoid direct HTTP access from controls. -* Keep external integrations behind focused services. -* Avoid circular dependencies. -* Keep feature boundaries clear. -* Do not create shared utility classes for unrelated functionality. -* Keep shared code genuinely reusable. -* Minimize global state. -* Avoid static service access. +* Check whether the app targets .NET Framework or .NET (8, 9, 10, or 11) before using newer APIs, and do not migrate between them as a side effect of another task. Use the C# version the project targets (.NET Framework 4.x defaults to C# 7.3). +* Prefer MVVM for non-trivial views and keep code-behind limited to view-specific behavior. +* Keep database, HTTP, and other external access behind focused services; never call them from views, controls, or directly from view models. +* Avoid static service access and global state. ## Dependency Injection -Follow the C# architecture rule for general dependency injection, plus: - * Register views and view models as transient unless they hold intentionally shared state; register shared services as singletons only when they are thread-safe and stateless or own deliberately shared state. * Do not resolve services from `App.Current` or a static container inside view models; inject them. * Create EF Core contexts per operation through `IDbContextFactory` (see the C# architecture rule). ## Testing -* Keep ViewModels testable without a UI thread where practical. -* Test behavior rather than implementation details. -* Test domain and application logic independently from WPF. -* Avoid brittle tests coupled to XAML structure. -* Keep UI automation tests focused on critical flows. -* Mock external boundaries rather than internal details. -* Keep tests deterministic. -* Avoid real network, database or filesystem dependencies in unit tests unless explicitly intended. - -## Code Quality - -Follow the C# coding-style and testing rules, plus: - -* Treat binding errors as defects: check the debugger output or XAML binding failures diagnostics for failed bindings after UI changes. +* Keep view models testable without a UI thread, and test domain and application logic independently from WPF. +* Avoid tests coupled to XAML structure, and keep UI automation tests to critical flows. ## Performance -* Keep the UI thread responsive. -* Minimize visual tree depth. -* Keep virtualization enabled (see the virtualization section of the collections rule). -* Avoid unnecessary bindings. -* Avoid unnecessary converters. -* Avoid unnecessary resource lookups. -* Avoid unnecessary property change notifications. -* Avoid frequent full collection refreshes. -* Avoid loading large datasets eagerly. -* Load images as the images section of the resources rule defines, and freeze `Freezable` objects where practical. -* Reuse immutable resources where appropriate. -* Avoid unnecessary animations. -* Avoid high-frequency timers on the UI thread. -* Measure startup time, UI responsiveness, memory usage and rendering performance before micro-optimizing. +Measure startup, UI responsiveness, memory, and rendering before optimizing, and work in this order: UI architecture, UI thread blocking, data loading and I/O, virtualization, visual tree complexity, binding and notification frequency, rendering and images, memory retention, allocations, then CPU micro-optimizations. -## Performance Priority - -Prioritize WPF performance work in this order: - -* UI architecture -* UI thread blocking -* Data loading and I/O -* Virtualization -* Visual tree complexity -* Binding and notification frequency -* Rendering and images -* Memory retention and leaks -* Allocations -* CPU micro-optimizations - -Never optimize based purely on assumptions. +* Keep the UI thread responsive and virtualization enabled (see the collections rule). +* Keep visual trees shallow, and avoid unnecessary bindings, converters, resource lookups, property notifications, and full collection refreshes. +* Load large datasets incrementally, load images as the resources rule defines, and freeze `Freezable` objects where practical. +* Avoid unnecessary animations and high-frequency timers on the UI thread. diff --git a/shared/rules/wpf/references/collections-and-xaml.md b/shared/rules/wpf/references/collections-and-xaml.md index c94332a..dff07ee 100644 --- a/shared/rules/wpf/references/collections-and-xaml.md +++ b/shared/rules/wpf/references/collections-and-xaml.md @@ -4,42 +4,22 @@ Apply these rules when binding collections, writing XAML, building layouts, or r ## Collections -* Use `ObservableCollection` only when collection change notifications are required. -* Do not use `ObservableCollection` as a general-purpose collection. -* Use `List` or other suitable collections for non-observable internal data. +* Use `ObservableCollection` only when bindings need change notifications; use `List` or other suitable collections for internal data. * Use incremental `Add` and `Remove` for small changes. For bulk changes, assign a new collection instance or raise a single `Reset`; never raise multi-item `Add`, `Remove`, or `Replace` notifications to WPF bindings, because `ListCollectionView` throws `NotSupportedException` for range actions. * Wrap sort and filter changes in `ICollectionView.DeferRefresh()`. * Mutate bound collections on the UI thread. Use `BindingOperations.EnableCollectionSynchronization` only when off-thread mutation is unavoidable. -* Avoid exposing mutable internal collections unnecessarily. -* Prefer read-only views where consumers should not modify data. +* Expose read-only views where consumers should not modify data. ## XAML -* Keep XAML readable and focused. -* Avoid excessively large view files. -* Split complex views into focused controls when it improves maintainability. -* Use resources for repeated values and styles. -* Avoid magic numbers in XAML. -* Keep styles and templates consistent. -* Avoid excessive inline styling. -* Prefer reusable resources over duplicated markup. -* Avoid deeply nested panels. -* Keep visual trees as shallow as practical. -* Use semantic control choices. -* Avoid unnecessary containers. -* Do not overuse triggers when simpler state representation is possible. -* Keep templates understandable. -* Avoid XAML tricks that make behavior hard to discover. +* Split large views into focused controls, and use resources and styles for repeated values instead of inline styling or magic numbers. +* Choose controls by meaning (a `Button` for actions, not a styled `Border` with a click handler), and keep panels and visual trees shallow. +* Prefer simple state in the view model over complex triggers and XAML tricks that hide behavior. ## Layout -* Prefer `Grid` for structured layouts. -* Use `StackPanel` only where its layout behavior is actually appropriate. -* Avoid unnecessary nested panels. -* Avoid fixed sizes unless the design requires them. -* Prefer responsive sizing with `Auto` and `*`. -* Avoid layout configurations that cause excessive measure/arrange passes. -* Be careful with large visual trees inside scrolling containers; see the virtualization section. +* Prefer `Grid` with `Auto` and `*` sizing for structured layouts; use `StackPanel` only where its unbounded stacking is intended, and avoid fixed sizes unless the design requires them. +* Avoid layouts that cause repeated measure and arrange passes, and large visual trees inside scrolling containers (see the virtualization section). ## Virtualization diff --git a/shared/rules/wpf/references/commands-and-async.md b/shared/rules/wpf/references/commands-and-async.md index e11f7f9..bd00e1f 100644 --- a/shared/rules/wpf/references/commands-and-async.md +++ b/shared/rules/wpf/references/commands-and-async.md @@ -4,28 +4,16 @@ Apply these rules when implementing commands, async operations, UI-thread work, ## Commands -* Prefer commands over click handlers for ViewModel-driven actions. -* Keep command execution focused. -* Avoid putting large workflows directly inside command implementations. -* Keep `CanExecute` logic cheap. -* Refresh command availability only when relevant state changes. -* Avoid command implementations with hidden side effects. +* Prefer commands over click handlers for view-model actions. Keep command bodies focused, delegate large workflows to services, keep `CanExecute` cheap, and refresh it only when relevant state changes. * Implement async commands with the project's MVVM library (for example CommunityToolkit.Mvvm `AsyncRelayCommand` or `[RelayCommand]`): disable re-entry unless concurrent runs are intended, expose cancellation for long operations, and surface failures to the user. -* Never use `async void` except for true event handlers. +* Use `async void` only for true event handlers, and wrap their bodies in `try`/`catch` (see the C# async rule). ## Async and Threading -* Keep async operations asynchronous throughout the call chain. -* Avoid `.Result`, `.Wait()` and other synchronous blocking of async work. -* Do not block the UI thread. -* Run I/O asynchronously. -* Move expensive CPU work off the UI thread only when necessary. +* Follow the C# async rule; in WPF, never block the UI thread, run I/O asynchronously, and move measured CPU-heavy work off it. * Let `await` resume on the UI thread in view models instead of calling the Dispatcher. When marshaling is unavoidable, inject a dispatcher abstraction; never use `Application.Current.Dispatcher` in view models, which breaks testing without a UI thread. * Do not use the Dispatcher to hide incorrect threading design. -* Support `CancellationToken` for cancellable long-running operations. -* Cancel obsolete work when views or selections change. -* Prevent race conditions caused by overlapping async operations. -* Handle exceptions from background operations explicitly. +* Cancel obsolete work when views or selections change, prevent overlapping operations from overwriting newer results, and handle exceptions from background work explicitly. ## UI Thread @@ -35,10 +23,5 @@ Apply these rules when implementing commands, async operations, UI-thread work, ## Events -* Avoid unnecessary event subscriptions. -* Unsubscribe from long-lived publishers when required. -* Prevent memory leaks from event handlers. -* Use `WeakEventManager` where the publisher lives significantly longer than the subscriber. -* Keep event handlers small. -* Do not use events as hidden global communication channels. -* Avoid excessive event chaining. +* Unsubscribe from long-lived publishers, or use `WeakEventManager` where the publisher lives much longer than the subscriber, to prevent leaks. +* Keep event handlers small, and do not use events as hidden global communication channels or long chains. diff --git a/shared/rules/wpf/references/mvvm-and-binding.md b/shared/rules/wpf/references/mvvm-and-binding.md index 3349729..7b9194a 100644 --- a/shared/rules/wpf/references/mvvm-and-binding.md +++ b/shared/rules/wpf/references/mvvm-and-binding.md @@ -4,61 +4,28 @@ Apply these rules when writing view models, data bindings, property notification ## MVVM -* Keep ViewModels focused on presentation state and commands. -* Do not put UI element references into ViewModels. -* Do not access `Window`, `UserControl`, `DispatcherObject` or visual tree elements from ViewModels. -* Avoid direct navigation, dialogs or message boxes from ViewModels without an abstraction when testability matters. -* Prefer explicit application services for navigation, dialogs and external interactions. -* Keep domain logic outside ViewModels. -* Do not use ViewModels as general-purpose service containers. -* Keep ViewModel dependencies minimal. -* Prefer immutable or readonly state where practical. -* Avoid duplicated derived state. -* Keep state transitions predictable. +* Keep view models to presentation state and commands; keep domain logic in services. +* Never reference `Window`, `UserControl`, `DispatcherObject`, or other visual tree elements from view models. +* Open dialogs, message boxes, and navigation through application services, not directly from view models. +* Keep dependencies minimal, derive state instead of duplicating it, and keep state transitions predictable. ## Data Binding -* Prefer data binding over manual UI synchronization. -* Use strongly typed properties. -* Use appropriate binding modes. -* Prefer `OneWay` when two-way updates are not required. -* Use `TwoWay` only when the UI must modify the source. -* Avoid unnecessary `UpdateSourceTrigger=PropertyChanged` for expensive operations. -* Keep binding paths simple and stable. -* Avoid deeply nested binding paths. -* Do not hide broken bindings. -* Treat binding errors as real defects. -* Use `FallbackValue` and `TargetNullValue` only when they reflect intended behavior. -* Avoid excessive converters. -* Prefer exposing correctly shaped state from the ViewModel over complex converter logic. -* Avoid `MultiBinding` when simpler state modeling is clearer. -* Do not put business logic into converters. +* Prefer data binding over manual UI synchronization, with strongly typed properties and short, stable binding paths. +* Use `OneWay` unless the UI must modify the source, and avoid `UpdateSourceTrigger=PropertyChanged` when the update is expensive. +* Treat binding errors as defects: check the debugger output or XAML binding failure diagnostics after UI changes, and use `FallbackValue` and `TargetNullValue` only for intended behavior, not to hide broken bindings. +* Expose correctly shaped state from the view model instead of converter or `MultiBinding` logic, and never put business logic in converters. ## Property Change Notifications -* Implement property change notifications consistently. -* Avoid raising `PropertyChanged` unnecessarily. -* Raise notifications only when values actually change. -* Keep dependent property notifications explicit. -* Avoid hidden notification chains that are difficult to reason about. -* Prefer reusable base implementations only when they reduce duplication without obscuring behavior. -* Use the project's MVVM library for notifications. Without one, prefer CommunityToolkit.Mvvm source generators (`[ObservableProperty]`, `[RelayCommand]`; on partial properties from 8.4.1 with C# 14) or a base class using `[CallerMemberName]`. Avoid reflection- or proxy-based notification frameworks unless the project already uses one. +* Raise `PropertyChanged` only when a value actually changes, and keep dependent notifications explicit instead of hidden chains. +* Use the project's MVVM library for notifications. Without one, prefer CommunityToolkit.Mvvm source generators (`[ObservableProperty]`, `[RelayCommand]`; on partial properties from 8.4.1, which requires C# 14) or a base class using `[CallerMemberName]`. Avoid reflection- or proxy-based notification frameworks unless the project already uses one. ## Dependency Properties -* Use dependency properties only when WPF property-system behavior is required. -* Do not use dependency properties as a replacement for normal CLR properties. -* Keep metadata and callbacks lightweight. -* Avoid expensive work in property-changed callbacks. -* Avoid callbacks with hidden side effects. -* Validate or coerce values only when the control contract requires it. -* Do not expose mutable default values in dependency property metadata. +* Use dependency properties only when the WPF property system is required, not as a replacement for CLR properties. +* Keep metadata and property-changed callbacks lightweight and free of hidden side effects, coerce or validate only when the control contract requires it, and never use mutable default values in metadata. ## Attached Properties and Behaviors -* Use attached properties and behaviors for reusable view-specific behavior. -* Do not use them to hide business logic. -* Keep behaviors focused and predictable. -* Clean up event handlers when behaviors are detached. -* Avoid global attached-property state. -* Prefer explicit behavior over complex XAML hacks. +* Use attached properties and behaviors for reusable view-specific behavior, never to hide business logic. Keep them focused, avoid global state in them, and clean up event handlers when they detach. diff --git a/shared/rules/wpf/references/resources-and-lifecycle.md b/shared/rules/wpf/references/resources-and-lifecycle.md index ea0683b..8d8d541 100644 --- a/shared/rules/wpf/references/resources-and-lifecycle.md +++ b/shared/rules/wpf/references/resources-and-lifecycle.md @@ -4,34 +4,17 @@ Apply these rules when managing resources and styles, windows and dialogs, navig ## Resources and Styles -* Use shared resources for repeated styles, brushes, templates and dimensions. -* Keep resource dictionaries focused. -* Avoid giant global resource dictionaries. -* Prefer feature-level resources when styles are not truly global. -* Use `StaticResource` by default. -* Use `DynamicResource` only when runtime resource replacement is required. -* Avoid excessive dynamic resource lookups. -* Keep theme resources separated from application logic. -* Avoid hardcoded colors and dimensions when design tokens or resources already exist. +* Use shared resources for repeated styles, brushes, templates, and dimensions, in focused dictionaries at feature level unless truly global; avoid hardcoded colors and sizes when resources exist. +* Use `StaticResource` by default and `DynamicResource` only where runtime replacement is required, such as theme switching. ## Windows and Dialogs -* Keep window lifecycle explicit. -* Avoid creating duplicate windows unintentionally. -* Do not keep hidden windows alive without a reason. -* Separate dialog logic from business logic. +* Keep window lifecycle and `Owner` relationships explicit, avoid duplicate or hidden windows kept alive without reason, and set `ShutdownMode` deliberately instead of relying on accidental window lifetime. * Show dialogs through the dialog service described in the MVVM rule. -* Keep ownership relationships explicit. -* Avoid application shutdown behavior that depends on accidental window lifetime. ## Navigation -* Keep navigation state explicit. -* Avoid coupling ViewModels directly to concrete views. -* Avoid service locator patterns for view resolution. -* Keep navigation history intentional. -* Dispose or release navigation targets when they are no longer required. -* Do not retain entire navigation graphs unnecessarily. +* Keep navigation state and history explicit, map view models to views without service locators, and release navigation targets that are no longer needed. ## Memory Management @@ -45,11 +28,7 @@ Apply these rules when managing resources and styles, windows and dialogs, navig * Closures * Collection views * Binding-related references: binding to a CLR property of a source that does not implement `INotifyPropertyChanged` keeps the source alive; bind only to `INotifyPropertyChanged` or dependency-property sources. -* Dispose resources correctly. -* Stop timers and background work when no longer needed. -* Avoid retaining closed windows or unloaded views. -* Do not keep unnecessary references to visual elements. -* Profile memory when long-running applications continuously grow. +* Dispose resources, stop timers and background work, and release closed windows, unloaded views, and visual element references. Profile memory when a long-running app keeps growing. ## Images and Media diff --git a/shared/rules/wpf/references/security-and-errors.md b/shared/rules/wpf/references/security-and-errors.md index cbb6c54..bb98477 100644 --- a/shared/rules/wpf/references/security-and-errors.md +++ b/shared/rules/wpf/references/security-and-errors.md @@ -4,8 +4,7 @@ Apply these rules when a WPF application handles secrets, files, processes, untr ## Security -* A desktop client cannot keep a secret from its user. Never ship service credentials or API keys in the application; use per-user authentication (for example MSAL with the Windows broker) and server-side authorization. -* Store user tokens and other per-user secrets with DPAPI (`ProtectedData` with `DataProtectionScope.CurrentUser`) or Windows Credential Manager, never in plain settings, `app.config`, or files. +* Follow the client app security rule (`rules-security-clients`): no service secrets in the app, server-side authorization, and per-user secrets only in DPAPI (`ProtectedData` with `DataProtectionScope.CurrentUser`) or Windows Credential Manager, never in settings, `app.config`, or files. Use per-user authentication such as MSAL with the Windows broker. * Follow the C# deserialization rule. Never pass untrusted XAML to `XamlReader.Load` or `XamlReader.Parse`, which can instantiate arbitrary types, and treat clipboard and drag-and-drop payloads from other processes as untrusted input. * Run with standard user rights; request elevation only for the specific operation that needs it, never for the whole application. @@ -22,7 +21,7 @@ Follow the C# safety and error-handling rule, plus: * Show users clear, actionable messages instead of raw exception text. * Wire `Application.DispatcherUnhandledException`, `TaskScheduler.UnobservedTaskException`, and `AppDomain.CurrentDomain.UnhandledException` once at startup to log the failure and decide whether the app can continue. -* Wrap the body of every `async void` event handler in `try`/`catch`, and do not start fire-and-forget tasks whose exceptions nobody observes. +* Do not start fire-and-forget tasks whose exceptions nobody observes. ## Logging @@ -33,5 +32,4 @@ Follow the C# logging rule (message templates, no secrets), plus: ## Validation * Implement input validation in view models with `INotifyDataErrorInfo` (or the project's MVVM library, such as CommunityToolkit.Mvvm `ObservableValidator`); keep complex validation out of XAML `ValidationRule`s. -* Display validation errors consistently and preserve user input on recoverable errors. * UI validation is not a security boundary; validate again in the domain or backend.