Search code examples
wpfmvvmdata-bindingcaliburn.micro

MVVM: Should I bind the textboxes directly to the model or should I create a full property first?


So I have a textbox like this:

<TextBox x:Name="FirstName" Width="100" />

and I have a model like this:

public class Person
{
    public string FirstName { get; set; }
}

Should my viewmodel look like this:

private Person _person;

public string FirstName
{
    get => _person.FirstName;
    set => _person.FirstName = value;
}

or

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set
    {
         _firstName = value;
         NotifyOfPropertyChange(FirstName);
    }
}

and then just create the person object later?


Solution

  • There is at least one good reason that you should not bind your view model property to your model. The view model property is bound to whatever the user cares to enter which may or may not be valid input so far as your model is concerned. If you effectively use the model as you are doing then you will have to make sure that your model is able to be put into a potentially invalid state. This is something that I would be loath to do. The view model is there to receive input from the user. Whilst you may be able to ensure that the view model state is always valid by specifying valid state to the input control (like the name must not exceed 100 characters in this case) there may be invalid input that you are unable to stop the user entering by precluding the input in the input control. Those states will then need to be handled by the view model itself.

    Whilst it can be a pain duplicating a load of properties between the view model and model they are not performing the same job.