# WPF Resources, Windows, and Lifecycle Apply these rules when managing resources and styles, windows and dialogs, navigation, memory, or images in WPF. ## 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. ## 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. * 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. ## Memory Management * Watch for memory leaks caused by: * Event subscriptions * Timers * Static references * Long-lived services * Cached views * 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. ## Images and Media * Decode images at display size with `BitmapImage.DecodePixelWidth` or `DecodePixelHeight`. * Load file-based images with `BitmapCacheOption.OnLoad` and close the stream, so the file is not locked. * Call `Freeze()` on immutable bitmaps and brushes, and cache images only with a clear memory limit.