I have a User Control that displays/manages one or more Addresses for an entity (employee, business, etc).
I have leveraged this User Control from various views - encapsulating the UI of an address within the control.
I have several ViewModels that hold/expose an Address Collection from various different perspectives - each of which is usually managed by a different ViewModel (one ViewModel fo开发者_运维知识库r each View)
I have passed the appropriate DataContext to the user control, meaning that although I have various ViewModels that expose the Address Collection - I can pass the appropriate context via the DC Binding.
My question then becomes where do I put the Command Logic for adding and removing addresses? I do not want to put commands that are identical in each view model, as that would be simply repeating code.
Being new to MVVM, would I just create a class with an IAddressCommand interface - and then stub out the commands in each of the ViewModels? Do I just encapsulate a view model, within another Viewmodel?
Thoughts?
Regards Richard
If the commands are the same for each type of address, then consider having a base ViewModel from which Address ViewModels inherit. The common command code can be placed in the base class.
Provide a service (not a ViewModel) that can tie these components together if you are certain you need a 1:1 approach with regard to your ViewModels:View. You would then make a call to the service within the ViewModel which would take care of adding/removing addresses from the underlying collection. This service can then be consumed by multiple ViewModels as needed.
If you are willing to adjust your design; make use of a single ViewModel or scale it back which could provide the ability to add/remove addresses from the underlying collection and can then be consumed and used by multiple Views.
IMHO going the first route and abstracting this workload into a service would be the better approach; although either would suffice.
精彩评论