7

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 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! Also, 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 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?

Thanks for all clarifications.

4 Answers 4

6

The textboxes can and should definitely be populated through bindings in XAML when the ListView selection changes, eg:

<ListView Name="people" .../>

<TextBox Text="{Binding ElementName=people, Path=SelectedItem.FirstName}"/>

Or to reduce coding, put the text boxes in their own panel with a DataContext set, eg:

<Grid DataContext="{Binding ElementName=people, Path=SelectedItem}">
    <TextBox Text="{Binding Path=FirstName}"/>
    <TextBox Text="{Binding Path=LastName}"/>
</Grid>

Validation can be hooked-up in XAML, but the code that does the validating is typically implemented in a class. There's a convenient abstract class in System.Windows.Controls called ValidationRule that can be used to quickly create a validator. See this blog post for an example.

6

The only time I start dropping code into the code-behind files is when I cannot put it in the ViewModel or deeper in the object graph.

For example, you're first situation is, as mentioned above by C. Lawrence Wenham, completely solvable in XAML code. There is no need to resort to the code-behind to achieve this effect. And this example can be expanded to interactions with a collection that isn't necessarily presented in a control like a listbox. You can write XAML code the responds to changes in the current item in a collection in the ViewModel via binding.

Your second situation can also achieved through dvalidation facilities within the ViewModel and databinding to those facilities with your XAML. IDataErrorInfo is a great mechanism that is built in for just this purpose. Here is a nice little article demonstrating a simple use of IDataErrorInfo.

Examples of when you have to drop into code-behind are hopefully few and far between. One example I've encountered is when a control does not support ICommand and you can not bind functionality to a behavioral element, an example control being a ListBox. But there are some techniques to get around this limitation, as demonstrated in this great SO question. Also, in the event that you need to override rendering in custom controls, you'll need to do this in code-behind or in an inherited class.

Hope this adds a bit more useful information to the answers.

2
  • Nice answer,just one more question from my side. When the view has to have other modal windows say by clicking a button I will get a Messagebox. Do I need to create such windows in code-behind?
    – Arseny
    Apr 7, 2011 at 11:19
  • That's a tricky one. A "pure" messagebox (Yes/No/Cancel) for example would still be done in code-behind but I find there are much better ways to create a user experience. Now, a modal window that is doing more than just yes/no/cancel functionality should generally have a viewmodel and accompanying view for presentation. Here is a great SO question/answer on this very topic. stackoverflow.com/questions/454868/…
    – Dave White
    Apr 7, 2011 at 15:39
2

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 :-)

2

You can use a validation rule for your binding. It won't show a message box (although it would probably be possible), but you can define an ErrorTemplate that shows the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.