wpfmvvmcode-behind

WPF: Where does MVVM stop and code-behind begin?


I have created a Window which has a ListView to display a collection of persons. There are also 3 TextBoxes that are supposed to display the person's first and last name, and an age. Finally, there's a Button to save the new person data entered in those TextBoxes.

Loading persons into the ListView is done by implementing MVVM. Works like a charm! Adding new people to the collection by clicking the Button is also done through MVVM.

But there are two use cases that I am not sure whether it is wiser to use commands, i.e. MVVM, or just plain code-behind. The use cases are:

  1. When user selects a person from the ListView, the TextBoxes should show the person details.
  2. When user types types characters instead of digits in the TextBox that displays the person's age, she or he should be warned that the entered data is incorrect.

The reason why I am in doubt whether I should use MVVM or code-behind is because both use cases are related to view only (GUI), i.e. there is no interactivity with the model or application business logic. The ListView item source is bound to a collection of persons ObservableColleciton<Person> and all data related to the selected person is already passed to the view when the ListView is populated with items. In the second use case, again, there is no need to go to ViewModel in order to let it fire the message box about the wrong user input. How about creating a validation callback in the age dependency property of the ViewModel class instead?


Solution

  • The main motivation behind MVVM is separation of concerns, i.e. separate logic from the presentation. What you are describing (search and validation) looks more "logic" to me, so I would put it in the ViewModel (assuming it cannot be performed with databinding of course).

    [*] just saying for educational purposes, many designers are more c# competent than me :-)