I have some controls which are bound to individual domain objects. I have to implement some basic update operations to the database via those objects. I'm using MVVM Command binding to update database. The problem is the Cancel button which basically reloads the original values. I have temporarily mad开发者_Python百科e it reload the objects from database, but have to change it soon.
Deep copying and manually syncing the objects didn't work since the objects don't allow easy cloning.
Setting UpdateSourceTrigger to Explicit of Binding and calling UpdateSource manually seem to be the best solution, but couldn't find a way to implement it, since I don't have direct access to view controls from view model (or command)
Any ideas ?
I remember using this article when struggling with the UpdateSourceTrigger Explicit. Later I had the same problem (I needed access to the view Controls). That was when I discovered that View Model is not something to maintain the state of the WPF View, but also a way to present the data and in this case your data is are some entities hydrated from the database.
I would have something like this:
[WPF View Model -> Entity View Model] -> Entity VM to Entity translation -> Database.
Inestead of this in your ViewModel:
public ObservableCollection<MyEntity> MyEntities
Have this:
public ObservableCollection<MyEntityViewModel> MyEntities
Where MyEntityViewModel
is a VM of my Entity
Let me explain a little more: The WPF View Model should present the data wrapped in VM. This is for presentation purposes. What happend if you have a quite complex demographic object graph but you only need to display Name, Birth Date and Blood Quantum ? Its far more easy to create a view model object to wrap those three properties than navigate the object graph. That's why tools like automapper exists.
What is the benefit of all this?
You don't need to fake the object graph to do your tests
You don't tie you entities to the ViewModel. If you cancel, you don't need to do a re get or something like that. you are not touching the enties except when validation succeeds.
Of course, this maybe doesn't fit all scenarios, and maybe you can think of something in between.
HTH
精彩评论