Getting Window from view model

后端 未结 1 797
余生分开走
余生分开走 2020-12-17 06:01

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

相关标签:
1条回答
  • 2020-12-17 06:18

    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;
    }
    
    0 讨论(0)
提交回复
热议问题