In this video, I answer the popular MVVM question, “How to Close Windows from a ViewModel”. When you’re developing WPF applications using the MVVM design pattern, the number one rule is “no UI elements in the ViewModel”. Well, if I am not allowed to have UI elements in the ViewModel, how on earth do I close windows from a ViewModel? Easy! With a simple layer of adbstraction.
I will teach you how to leverage the power of interfaces to abstract away the Window object from the ViewModel and still have the ability to close Windows from your ViewModel.
Not only that, but we will see how we can even prevent the Window from closing, even when clicking on the Window’s close button (the X in the top riht corner of the Window), using business logic in our ViewModel by leveraging the flexibility of our abstraction.
I’ll even show you how to reduce code duplication by consolidating our abstraction login into an AttachedProperty which can be used on any Window in our application. Write once, use everywhere!