Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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)?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
Interesting; so if I'm understanding right, the ViewModel is more about a 1-1 conversion of a model's data into a presentable form, and any number of views can choose to represent any subset of the data in a ViewModel. Would that be correct? –  Steve Evers Apr 12 '11 at 15:34
    
Not necessarily 1-1, but the ViewModel should represent a single business object for UI rendering. If you had a case when a single database ('model') object related to two distinct business objects, you'd create two viewmodels. –  Kirk Broadhurst Apr 13 '11 at 14:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.