开发者

ViewModel -> Model interaction

Suppose I have a WPF/MVVM application for managing some hypothetical customers :).

Domain model contains an entity named Customer (represented as a POCO in code).

The main screen contains a grid, bound to a view model (CustomersViewModel) that loads its data from Repository< Customer>.

The main screen also allows to create new customers (and save it to the DB).

Suppose I need to implement 'add customer' use-case. The most obvious approach is as follows:

  1. Present the user with a dialog window to be filled out with new customer data.
  2. Handle 'Save' button click in the ViewModel.
  3. Create customer (var new_customer = new Customer(..)) domain object using the data from the dialog (step 1).
  4. Call Repository< Customer>.Save(new_customer) to save the new customer to the DB.
  5. Reload CustomersViewModel with fresh data from the DB so that newly开发者_如何学运维 added customer is visible in the grid.

Personally I don't like this 'quick-and-dirty' way (because of need to reload the full list of customers from DB every time a new customer is added).

Can anyone suggest a better approach (that wouldn't require refreshing the customer list from the DB)??? I feel there gotta be some best practice for handling scenarios like that:) ).

Thanks in advance!


If the saving of the Customer is successful, why can't you just add that single Customer instance to your collection of customers? No need to re-load all customers unless the user explicitly refreshes the view (usually via a refresh button).


If you are loading the list in your view through a binding (to a list of customers) you can just add the new customer to that list and everything is alredy ;-)


I have a similar application where in the object is created in UI. I solve it by adding the object in VM and then syncing it with Model on click of Save button.

I am assuming you have a list of CustomerViewModel in CustomersViewModel to which the grid view is bound to. You can add a new CustomerViewModel object to the list in CustomersViewModel. While saving the ViewModel data back into the model, the model gets in sync with VM. No need to refresh VM back from Model unless somebody else apart from your app is changing the Model data.


You could create an ObservableCollection<Customer> and fill it with the customers from the database which you want to show in the View. When you add a new customer then add it to this collection as well as save it into the database. The CustomersView binds on the ObservableCollection and is updated automatically without the need to refresh the data from the database.

The BookLibrary sample application of the WPF Application Framework (WAF) shows how this can be done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜