Sometimes when developing a WPF application, I need to access a certain Window
(View
) from the corresponding ViewModel
, to perform or fire a method like this for example:
//In the MainWindowViewModel
MainWindowView.Hide();
But that's not really easy, and even it violates MVVM because the ViewModel
shouldn't know anything about the View, so I started doing this instead:
//In the MainWindowViewModel
Application.Current.MainWindow.Hide();
This becomes impractical when dealing with other Windows (Views):
//In the AnotherWindowView
Application.Current.Windows.OfType<AnotherWindowView>().First().Hide();
So I decided to make a solution, a helper class, in which, using a method, I give the ViewModel
and I get back the corresponding View, using the DataContext
of the View, the solution looks like this:
The Class:
public static class ViewsAccessibility
{
public static Window GetCorresponingWindow(ViewModelBase viewModel)
{
var windowAccessibility = new WindowAccessibility(viewModel);
return windowAccessibility.CorrespondanteWindow;
}
private class WindowAccessibility
{
public Window CorrespondanteWindow { get; private set; }
public WindowAccessibility(ViewModelBase viewModel)
{
var windows = Application.Current.Windows.OfType<Window>();
CorrespondanteWindow = (from window in windows
where window.DataContext.Equals(viewModel)
select window).First();
}
}
}
The use:
//In the MainWindowViewModel
ViewsAccessibility.GetCorresponingWindow(this).Hide();
Is this a good practice and does it violate MVVM or not?