I have created a custom messageBox Window to replace the typical MessageBox.
My custom messageBox (child Window) needs parent window to be passed as an argument. The
How can I get the Window associated to the view model?
You could inject the view model with an interface that the window implements:
public interface IView
{
double Top { get; }
double Left { get; }
double Height { get; }
double Width { get; }
}
public partial class MainWindow : Window, IView
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel(this);
}
}
public class ViewModel
{
private readonly IView _view;
public ViewModel(IView view)
{
_view = view;
}
//...
}
Then the view model knows only about an interface (which maybe should be called something else than IView).
If you want an ugly and non-MVVM friendly shortcut, you could use the Application
class:
var win = Application.Current.MainWindow;
A factory class to create everything:
public MainWindow WindowFactory()
{
MainWindow mainWindow = new MainWindow();
ViewModel viewModel = new ViewModel();
mainWindow.DataContext = viewModel;
return mainWindow;
}