tags:

views:

70

answers:

1

Hi,

I'm asking myself how to apply MVVM in the following scenario correctly: Let's assume I have simple Master-Detail data, like a person with 0-n addresses. The addresses should be displayed in a ListBox and the user should be able to trigger certian actions for each address.

So what I did is to create a VM which returns the person model and the addresses models. The problem then is, that I want to create buttons in the address DataTemplate. But to make the buttons work I need a command exposed by each address, which can be bound to the appropriate property on the button.

My question is, if it is really the correct approach to wrap (in this case) each address in another object which the exposes the necessary functionality? I would like to avoid that I have to maintain a second list of addresses view models, depending on the changes of the first list with the model objects.

tia Martin

+2  A: 

That sounds like the correct approach.

It is always very tempting to bind UI directly to a Domain Model class, but experience shows that you might as well always slide a ViewModel in between the UI and the Domain Model. This ensures that UI-specific members (such as the ICommand properties you mention) stay in the UI and does not invade the Domain Model.

In some cases, it might seem that the Domain Model almost fits, or even that it totally fits the intended UI. In these cases, it is very difficutl to resist the urge to simply bind the Domain Model directly to the View.

However, it is very likely that View-specific requirements may appear later on, and then you are faced with having to introduce a ViewModel at that time - and that will often be a time where you don't really have the time to do this.

It also makes your application architecture easier to understand if you can simply say: "All Domain objects are wrapped in a ViewModel that is then bound to the Views."

Mark Seemann
+1. Binding directly to models may seem easier at first, but eventually you almost always end up needing something that the model can't provide (usually commands)
Thomas Levesque