0
votes

Still trying to find good example of the more complex MVVM scenarios...

Suppose I have one viewmodel - PlayersViewModel that has a collection of Players. In one view I see the collection of Players and add/edit/delete.

Another view is teams, where I assign Players to Teams. So I have another viewmodel - TeamsViewModel. This view also needs a collection of Players. How do I keep the two player lists in sync so changes are shown in both views?

I see a number of options:

  1. Add a reference to PlayersViewModel to my Team view (as well as a reference to TeamsViewModel) and use the PlayersViewModel.Players collection in both views
  2. Have two different collections that reference the same underlying collection instance (somehow)
  3. Create a static property on the Player model like Player.All that returns the collection and the viewmodels manage Players by Player.Add(player), Player.Delete, etc. instead of PlayersViewModel.AddPlayer(player)?

I tend towards #1 at the moment and using app-wide resources so the Team view can call both viewmodels. But then how do I use the selected Players in my PlayersViewModel.Players collection in my TeamsViewModel to add them?

Help please!!

3

3 Answers

2
votes

My hard and fast rule is one ViewModel per View, so in my book you are on the right path. Don't confuse the PlayersViewModel with the Players data: the PlayersViewModel is oriented toward the Players View, NOT the Players data. In other words, the two are separate, so you do not need to reuse the PlayersViewModel in other ViewModels. I apologize if I'm not explaining this well...

If you need multiple ViewModels to display with the same instance of the data, then define the data at the App level rather than the Document level. You could make Players Static or you could have it implement the Singleton pattern: none of those things are specific to the ViewModel because the ViewModel merely consumes the resource.

0
votes

Use a single ViewModel. Let different views display only what they need. With regard to the collection of players: WPF allows you to have multiple views of the same collection and each with a different filtering/sorting/grouping. See Binding to Collections.

0
votes

Personnally, in order to be easier to understand, I have one viewmodel per view. This means each custom UserControl has its own ViewModel, dealing with its own actions. I'm working on a pretty big project with plenty of views, I think it is way cleaner to have one ViewModel per view. It helps me reading my architecture correctly, and therefore I won't mix roles in a unique ViewModel.

However, I cannot ensure you that's the best way to do. I started working in WPF/MVVM 2 weeks ago, I just figured out that it'd be easier to understand with this way (I am used to split my programs into as many classes as possible since I think it's easier to maintain)