MVVM Light & WPF - Binding Multiple instances of a Window to a ViewModel

前端 未结 2 2116
猫巷女王i
猫巷女王i 2020-11-27 19:38

I am working on my first project in MVVM and I\'ve chosen to use the MVVM Light Toolkit. I have a GameViewModel that handles business on the main screen of my g

相关标签:
2条回答
  • 2020-11-27 20:37

    Ok I put together a demo that should make this hopefully easier for you Download Link

    Functionality:

    • 3 Windows in Total (MainWindow, ModalWindow, NonModalWindow)
    • MainWindow has a TextBox you can type whatever you want into.
    • 2 buttons on the top will open the Modal / NonModal Window accordingly
    • Each window when opened will display the message that was in MainWindow's TextBox in a TextBlock inside them.
    • In each window you can tick a CheckBox to update the value in result's textblock in MainWindow (For the Modal Window this will kick in when modal window is closed. For NonModal changes can be seen asap)

    That's it for functionality,

    Concepts:

    • Registering Multiple VM's with the SimpleIoC and using GetInstance(...) to request them out.
    • Messenger class usage with a custom message type OpenWindowMessage
    • Opening Modal / Non Modal Windows from a parent VM staying true to the MVVM principles
    • Passing data between windows(just shown in NonModal)

    Important Note: - The method used in this example to set the non DP DialogResult from the modal window is not MVVM friendly cos it uses code-behind to set the DialogResult property on a Window.Closing event which should be avoided(If needing to be "testable"). My preferred approach is a bit long and is very well documented HERE(Mixture of question and answer). Hence why I ignored it for the sake of this sample.

    0 讨论(0)
  • 2020-11-27 20:43

    Follow up to Viv, I modified the sample to include an example of opening the window without using a code behind.

    Sample project is here.

    I'm utilizing the ViewModelLocator singleton with a static method that news up the viewmodel and window and Data Context instead of the code behind.

    Blog Post with Details. Let me know which method is preferable. I dislike using code behind, but there could be pro's and con's I'm missing.

    0 讨论(0)
提交回复
热议问题