Setters in ViewModels

by Noceo   Last Updated May 15, 2019 19:05 PM

So I have started reading some books and articles on architecture. They all state (put a little simply) that you should never let your view access the model directly, when using a Model-View-ViewModel (MVVM) pattern. Instead there should be a view model for each model.

One of the ideas is, as I understand it, that formatting can be done in the view model, which will then mainly contain strings. An example could be a person model which looks like this:

class PersonModel
{
    public string FullName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public decimal YearlyIncome { get; set; }
}

Now a read only view model, could then look something like this:

class PersonViewModel
{
    private PersonModel _person;

    public PersonViewModel(PersonModel person)
    {
        _person = person;
    }

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

    public string DateOfBirth 
    {
        get { return _person.DateOfBirth.ToString("dd.MM.yyyy"); }
    }

    public string YearlyIncome
    {
        get { return _person.YearlyIncome.ToString("N2"); }
    }
}

Now this approach is quite nice, since you don't need to consider string formats in something like XAML (if you are using WPF) or whatever GUI stuff you are working with.

But here is my question; what do I do with the setters using this approach? They obviously need the same input type (string) as the getter, at least when using C# with WPF. I could of course make a custom setter, like this:

public string DateOfBirth
{
    get { return _person.DateOfBirth.ToString("dd.MM.yyyy"); }
    set { _person.DateOfBirth = DateTime.Parse(value); }
}

Is this a viable approach or am I way off, in my understanding of how to use view models?

Tags : c# mvvm


Related Questions


Updated April 03, 2015 22:02 PM

Updated July 15, 2015 17:02 PM

Updated July 10, 2017 13:05 PM

Updated April 05, 2018 15:05 PM

Updated May 03, 2015 21:02 PM