A new WPF topic rule covers accessibility (AutomationProperties names and help text, keyboard access, visible focus, high contrast through SystemColors, automation peers for custom controls), DPI scaling in device-independent units with tests across scale factors and monitors, and the Fluent theme through ThemeMode on .NET 9 and later. The existing WPF rules lose about a quarter of their size by merging one-line generic bullets that the C# and shared rules already cover, while keeping the WPF-specific pitfalls. Duplicate async void and binding error guidance is merged, client secret handling defers to the client app security rule, the architecture rule asks to check .NET Framework versus .NET before using newer APIs, and the CommunityToolkit note states that partial properties require C# 14. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2.1 KiB
2.1 KiB
WPF Collections, XAML, Layout, and Virtualization
Apply these rules when binding collections, writing XAML, building layouts, or rendering large lists.
Collections
- Use
ObservableCollection<T>only when bindings need change notifications; useList<T>or other suitable collections for internal data. - Use incremental
AddandRemovefor small changes. For bulk changes, assign a new collection instance or raise a singleReset; never raise multi-itemAdd,Remove, orReplacenotifications to WPF bindings, becauseListCollectionViewthrowsNotSupportedExceptionfor range actions. - Wrap sort and filter changes in
ICollectionView.DeferRefresh(). - Mutate bound collections on the UI thread. Use
BindingOperations.EnableCollectionSynchronizationonly when off-thread mutation is unavoidable. - Expose read-only views where consumers should not modify data.
XAML
- 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
Buttonfor actions, not a styledBorderwith 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
GridwithAutoand*sizing for structured layouts; useStackPanelonly 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
- Keep UI virtualization enabled for large collections and use
VirtualizingPanel.VirtualizationMode="Recycling". - These settings silently disable virtualization:
ScrollViewer.CanContentScroll="False", grouping withoutVirtualizingPanel.IsVirtualizingWhenGrouping="True", a non-virtualizingItemsPanelsuch asStackPanelorWrapPanel, and placing the list inside aScrollViewerorStackPanelthat gives it unlimited height. - Verify virtualization with large data sets, and use paging or incremental loading for very large ones.