Search code examples
c#wpfmvvm

How does ViewModel to Model communication work in MVVM?


I want to change Model.Street and other Propeties of the Model and everything i try just seems too long, not right or too complicated. I dont wanna sound lazy but thats just how i am used to it.

  1. Example

I tried this but it feels like i just write the Model again

public class CustomerInfoViewModel : BaseViewModel
{
    public CustomerInfo Model { get; set; }
    public CustomerInfoViewModel()
    {
        Model = new CustomerInfo();
    }
    public CustomerInfoViewModel(CustomerInfo customerInfo)
    {
        Model = customerInfo;
    }

    public string Street
    {
        get
        {
            return Model.Street;
        }
        set
        {
            Model.Street = value;
            OnPropertyChanged();
        }
    }
}
  1. Example

I also found something like this but then a always add a field which also seems wrong.

public class CustomerInfoViewModel : BaseViewModel
{
    public CustomerInfo Model { get; set; }

    public CustomerInfoViewModel()
    {
        Model = new CustomerInfo();
    }

    public CustomerInfoViewModel(CustomerInfo customerInfo)
    {
        Model = customerInfo;
    }

    // Create a generic field setter method
    private void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propertyName);
        }
    }

    private string _street;

    public string Street
    {
        get => _street;
        set => SetField(ref _street, value);
    }

    // Add other fields and properties using the same pattern
}

Do i get something wrong about MVVM or is this an good/ok way of doing it, is there a better solution?


Solution

  • There are variable approaches to MVVM. Purists condemn binding to the model as a pattern-breaking practice. Personally, I tend to have a single model/vm class, when I am not yet sure whether I will be needing a separate view model counterpart. As soon as I need to add some calculated property, or some client-side data shaping over the model data, I switch to a dedicated ViewModel. In my opinion, super strict MVVM can cause some significant overhead, so I recommend against becoming a slave to the pattern, but taking the parts that work for you.