I have a form in a window which is opened to add a new instance of an entity. To later edit this entity, what is the best way to present the same form, except with the fields pre-populated?
Without a dirty hack (along the lines of setting a state [add/edit]) and violation of the single responsibility principle, I’m finding it hard to reuse the same view and view model. I’m currently thinking of inheriting from a base view model which contains all the duplicate VM code, but then I’m still stuck with 2 versions of an identical form. What’s the best way to do this whilst keeping it DRY?
I’m reasonably new to WPF, and I’m using the MVVM Light framework.
Use Automapper, it will basically make mapping between your entities and view models painless. Retrieve the entity in question, and map it to a view model to display on your form. You can either create a new view model and bind it to your view, or just re-use the same view model as long as you clear existing fields.
I would recommend having a state on your view model telling your UI whether you’re in ‘create’ or ‘edit’ mode. In my mind this doesn’t violate single responsibility; the view model is telling the UI how it should display itself. The actual edit and create functionality should be included in separate Command objects.
http://automapper.org/