lundi 27 mars 2017

C# MVVM How to dynamically create Views

I'm trying to create a memory game while strictly following the MVVM pattern to learn how to use it. Now I have a problem with creating views at run time.

I've created the following project structure:

  • Model project
  • -MemoryCardModel30
  • -Card
  • ViewModel project
  • -MainWindowViewModel
  • -CardViewModel
  • View project
  • -CardView
  • StartApplication project
  • -MainWindowView

The dependencies are as follows: StartApplication project -> View project -> ViewModel project -> Model project

After clicking a button on the MainWindowView the ICommand function for that button within the MainWindowViewModel will load a MemoryCardModel30 instance from the Model project. For each Card within the MemoryCardModel30 instance a CardViewModel will be created.

Now to the problems I face: How to create the CardView instances, how to link their DataContexts to the CardViewModels and how to arrange/assign the CardViews on the MainWindowView? The ViewModel project can't create Views as it has no dependency to the View project (would create a circular dependency and breaks the pattern). How to solve this issue while following the MVVM pattern?

P.S.: The CardViews need to be positioned exactly by x and y pos. which will require some complicated calculations which should go tho the corresponding CardViewModel. So some basic layouts like grid will not be sufficient I think.

Aucun commentaire:

Enregistrer un commentaire