How to open a modal window the MVVM way

I'm still trying to get a grip with WPF and MVVM and stumbled upon questions, where the easy way seems to violate the MVVM rules.

As far as I understood it, in MVVM the view model is not allowed to know about the view. So if I put views and view models in different assemblies, the view model assembly is not allowed to reference the view assembly.

So, here are my questions:

  • Let's say I have a MainView and a corresponding MainViewModel. The MainView has a button that is supposed to close the window and do some serious stuff before closing (for instance saving data and configurations). This button is bound to a CloseCommand in the MainViewModel, but how do I know in the MainViewModel which view to close. My easy (and wrong) ways would be either to give the MainViewModel an instance of the MainView on initialisation or to give the view-to-close as a command parameter. But both solutions violate the MVVM rule.

  • Let's say my MainView contains a TextBox bound to a string property of my MainViewModel. If the text, the user types in the TextBox, isn't unique enough, I'd like to open a new modal window in which the user can select his input out of various choices. To open a modal window in WPF you have to put the MainView in the Owner property of the new window. Therefore you need a reference to the MainView in the MainViewModel. Same problem exists, if you try to show a modal message box (a message box that is tied to the parent window and can't be put behind the parent window through mouse clicks or other user actions).

  • So, how is one supposed to do actions in the view model when you need knowledge about the view?

    Thanks for your help.


  • It seems that you wish to close the main window, and that is perfectly fine. As many things, this can be solved with a new level of abstraction. Lets say you have an interface called IApplication with a method Close() . And then lets say you have an implementation of the interface that might look something like:

    class ApplicationWrapper : IApplication
    {
        public void Close()
        {
            Application.Current.MainWindow.Close();
        }
    }
    

    Couldn't you inject the IApplication interface in the view model and call its Close method from the command?

  • I would propose MVVM Dialogs, but I am biased since I also am the author.

  • 链接地址: http://www.djcxy.com/p/56204.html

    上一篇: WPF:为什么CommandBindings只使用破坏MVVM的RoutedCommand?

    下一篇: 如何以MVVM的方式打开模式窗口