I have created a Window which has a ListView
to display a collection of persons. There are also 3 TextBox
es 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 TextBox
es.
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:
ListView
, the TextBox
es should show the person details.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?
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).
Keep in mind that the view is difficult to test, so if there's a chance that the logic you are implementing has significant errors that would be a reason to put it in the viewModel.
An alternative (semi-serious but usually effective) method to decide if something belongs to the model or to the viewModel is asking yourself what would happen if you give the view (the Window, UserControl or whatever) to your graphic designer (even if you don't have one, pretend you do). If you are ok with the idea that he could put his c#-incompetent[*] hands on the code behind (and make a mess out of it) it's generally a sign that the code is strictly presentation-related and can safely live in the view. Most times you'll end up moving it to the ViewModel.
[*] just saying for educational purposes, many designers are more c# competent than me :-)