# 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 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. * 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 `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` 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 * 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.