Anybody come across a clever way of closing a view in a viewmodel using MVVM?
Maybe there is a way of using binding to signal the view (window) to close?
I w
You can also do this using event. Though you need like 3 lines of codes in your view code behind (some MVVM purist don't like this);
In your viewmodel, you create an event that the view can subscribe to:
public event CloseEventHandler Closing;
public delegate void CloseEventHandler();
private void RaiseClose()
{
if (Closing != null)
Closing();
}
In your, view you subscribe to the event after your initializecomponent method as below:
public View
{
*//The event can be put in an interface to avoid direct dependence of the view on the viewmodel. So below becomes
//ICloseView model = (ICloseView)this.DataContext;*
ProgressWindowViewModel model = (ProgressWindowViewModel)this.DataContext;
model.Closing += Model_Closing;
}
private void Model_Closing()
{
this.Close();
}
You just simply call RaiseClose() when you are ready to close the View from the ViewModel.
You can even use this method to send message to the view from the viewmodel.
The event can be put in an interface to avoid direct dependence of the view on the viewmodel.