WPF MVVM How to close a window
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Windows Presentation Foundation (WPF) is a UI framework for building Windows applications. Model-View-ViewModel (MVVM) is a popular pattern used in WPF to separate concerns: the Model represents data and business logic, the View manages UI, and the ViewModel connects the two, serving as a middleman. Closing a window in an MVVM-based WPF application can be less intuitive than handling it directly due to the separation of concerns. This article explores various techniques to close a window within the MVVM paradigm, ensuring you adhere to this architectural pattern.
Challenges in Closing a Window in MVVM
In WPF applications, the View should directly handle UI operations like closing a window. However, the MVVM pattern dictates that these concerns are managed in the ViewModel, creating a challenge. The ViewModel doesn't have direct access to the View or its components, including window instances. Hence, closing a window requires a strategy that maintains this separation.
Common Techniques to Close a Window
1. Using Commands
WPF commands are a crucial aspect of the MVVM pattern. While commands don't directly close windows, they can invoke methods that influence the View behaviors indirectly.
Implementation Steps:
- Define a Command: In your ViewModel, define a command responsible for triggering the close operation.
Related reading
- WPF TextBox won't fill in StackPanel
- WPF updating the itemssource in a ListBox with an async method
- WPF User Control Parent
- WPF Window with transparent background containing opaque controls
- Wrap a delegate in an IEqualityComparer
- Wrapping ManualResetEvent as awaitable task
- Wrapping StopWatch timing with a delegate or lambda?
- Write to Windows Application Event Log without event source registration

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.