Is it common/correct using MVVM to expect multiple views and corresponding view-models for a particular model

design-patternsmvvm

Consider a somewhat contrived model that goes something like:

class Player
{
    public int Health;
    public int Ammo;
    public Weapon CurrentWeapon;
    public PhysicalState State
    {
        get
        {
            if (this.speed <= 0.1)
                return PhysicalSpeed.Standing;
            /* and so-on for Strafe_left, Running, etc. */
        }
    }
}

In the expected visual for such a game it is known that the heads-up display (HUD) will display things like Health and Ammo, whereas the avatar will show the weapon and the animation based on the physical state.

So, assuming you have a HUD_View and a Player_View that draw the HUD and the player respectively, is it correct, within the confines of MVVM to have 2 view-models for the Player model, that are only ever intended to expose a subset of information in the model or is it expected that the model will be split in two as well?

Is there anything that I'm missing? Can someone point me to, or provide a more concrete example of the correct solution (even if my thinking is correct, so that I might solidify my understanding here)?

Best Answer

No, I don't believe that it is expected to have a ViewModel per View.

Assuming that the HUDView & PlayerView represent the same conceptual object - that is, the same player in the same context, which in this case they do - then there's no need. You would simply be replicating an awful lot of code and making more work for yourself.

If you have some need to split into two ViewModels then by all means, do so. But I assume your ViewModel is going to be primarily shared across the two views - getting the Player object, updating properties on particular events, if/then functions. You should create just one instance of the ViewModel so that the HUD and Player views both point to the same data - you update a single property, and both the Views nicely update in turn.