Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining WPF MVVM View Model & Model Relationships

Tags:

c#

mvvm

wpf

this seems like a basic question but I can't figure out the best implementation. How do you manage the relationships between two view models and their corresponding models.

For instance, if you changed the Occupation property on PersonViewModel, how does that change trickle down to the Occupation property in the PersonModel.

The only way I can see it right now is publicly exposing the model in the view model, but I thought that defeated the purpose of MVVM - decoupling the model from the view.

internal class PersonViewModel : INotifyPropertyChanged
{
    private readonly PersonModel person;

    private OccupationViewModel occupation;

    public PersonViewModel(PersonModel person)
    {
        this.person = person;
    }

    public OccupationViewModel Occupation
    {
        get { return this.occupation; }
        set 
        { 
            if (!this.occupation.Equals(value))
            {
                this.occupation = value;
                this.person.Occupation = this.occupation.Occupation; // Doesn't seem right

                this.OnPropertyChanged(new PropertyChangedEventArgs("Occupation"));
            }
        }
    }
}

internal class OccupationViewModel : INotifyPropertyChanged
{
    public OccupationViewModel(OccupationModel occupation)
    {
        this.Occupation = occupation;
    }

    public OccupationModel Occupation { get; set; } // Is this right?
} 

internal class PersonModel
{
    public OccupationModel Occupation { get; set; }
}
like image 851
Patrick Avatar asked Jan 04 '11 20:01

Patrick


1 Answers

Your view-model is decoupling the model from the view. It seems like you may be confusing the concepts of the view and the view-model.

The view-model is both the gateway and the gatekeeper between the two -- it determines what makes it from the model to the view and from the view back to the model, and in what form.

You can set the model property in the VM setter, or not. You could save up state from the view, and only propagate those changes to the model when the user clicks "save." You could persist that state elsewhere so someone can come back and work on it more before persisting it to the view.

The view-model can know the model intimately, so the view doesn't have to know it at all.

I'm not sure I follow your concern about publicly exposing the model in the view-model. You haven't done that in your sample code. You've exposed an object that is the same type as you use in the model, but this is like using int for age in both the model and view-model -- you haven't exposed the actual model object; you still have control over whether and when the value in the view-model gets set on the model.

like image 141
Jay Avatar answered Oct 27 '22 00:10

Jay