开发者

MVVM Model with a list?

I have a silverlight wp7 application and I'm applying the MVVM pattern. The model contains a list of classes (the class type encapsulates stock ticker data), and that list is used in a View, along with an Item template.

My understanding is that in order for that List to work with Binding, it needs to be an observable collection (raising the PropertyChanged 开发者_如何学Pythonevent doesnt seem to do anything).

As such, how do I maintain a decoupling between my model which should be agnostic to the presentation, and the view that requires an observable collection?

Currently, in my View-Model, I dynamically create an observable collection using the data in the model.List. This seems like a kludge.


There are only two ways you can go about this:

  1. Have the Model expose an ObservableCollection itself. This means that you will not need any kludge in your ViewModel, but you might say that this is simply moving the problem elsewhere.

  2. Have the ViewModel expose an ObservableCollection it creates itself, like you do now. If the collection can be updated (which does not look like the case in your scenario), the ViewModel will also need to "take ownership" of the Model and propagate the changes back to the List.

I don't believe that what you do is a kludge. The Model is definitely totally decoupled from the presentation (View), as it's the ViewModel that needs to go to all the trouble to make things work. This is totally in the spirit of MVVM.


I agree that it is not a kludge, and for practical terms, having your model expose a observable collection, is the best solution, especially if you are going to update it from outside sources.

Your two other options are using a relay command from any source that can update the list to tell the viewmodel it needs to resync, or adding a handler in your viewmodel to the list's itemadded event, which would then add that item to your observable collection in your vm.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜