0

So let's say I have a view model, representing a student. The view model is corresponding to a student model, from which the data comes. What I am struggling with, is how to populate the fields in the view model. Do I simply forward reference the fields from the model (where possible) or do I have actual fields in the view model, which I then populate?

Example A - Forward referencing

public class StudentViewModel
{
    public StudentModel Student { get; set; }

    public string FirstName 
    {
        get { return Student.FirstName; }
    }

    public string LastName
    {
        get { return Student.LastName; }
    }

    // ...and so on
}

Example B - Using actual fields

public class StudentViewModel 
{
    public string FirstName { get; private set; }

    public string LastName { get; private set; }

    public void SetStudentProperties(StudentModel student) 
    {
        FirstName = student.FirstName;
        LastName = student.LastName;
    }
}

So obviously both of these examples are overly simplified and I have left out stuff like INotifyPropertyChanged, but I think you get the point. Are any of my approaches viable, or have I completely misunderstood the intend of view models?

I also considered using the constructor for input, but this makes me struggle with the depency injection framework (I am using Caliburn.Micro).

  • Just bind to Student.FirstName and Student.LastName directly. – Robert Harvey Jul 9 at 21:57
  • A ViewModel which simply displays some data from a datasource would be much different from a ViewModel which presents parts of a Model to the user for editing. So there's no one single approach. – Graham Aug 2 at 19:27
0

What problem are you trying to solve by duplicating the StudentModel properties in the StudentViewModel? Adding this type of facade wrapper does nothing except bloat the code base. Just include the StudentModel instance as a (read only) property of the StudentViewModel and bind directly to its properties.

Take a look at my blog posts concerning the division of labour between Model and ViewModel classes.

  • 1
    Obviosuly in the real use, there might be some derivative properties. A classic example could be a property for Age, which would be derived from DateOfBirth and only be part of the view model. – Noceo Jul 3 at 12:25
  • 1
    My blog posts include a methodology for handling such "non-data" properties. – Peregrine Jul 3 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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