# WPF Collections, XAML, Layout, and Virtualization Apply these rules when binding collections, writing XAML, building layouts, or rendering large lists. ## 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 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. ## 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. ## 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. ## Virtualization * Keep UI virtualization enabled for large collections and use `VirtualizingPanel.VirtualizationMode="Recycling"`. * These settings silently disable virtualization: `ScrollViewer.CanContentScroll="False"`, grouping without `VirtualizingPanel.IsVirtualizingWhenGrouping="True"`, a non-virtualizing `ItemsPanel` such as `StackPanel` or `WrapPanel`, and placing the list inside a `ScrollViewer` or `StackPanel` that gives it unlimited height. * Verify virtualization with large data sets, and use paging or incremental loading for very large ones.