开发者

Silverlight MVVM: how to avoid polluting my model while still implementing "add new item" for my datagrid?

开发者 https://www.devze.com 2022-12-14 08:37 出处:网络
I have a DataGrid. Right now it\'s binding to an ObservableCollection<Foo> in my model just great.

I have a DataGrid. Right now it's binding to an ObservableCollection<Foo> in my model just great.

But now I want to implement a user-friendly way to add a new item to the datagrid. It seems like I'll need to modify Foo to inherit from IEditableObject and INotifyPropertyChanged, which is kind of icky from a MVVM perspective in my mind---those seem more like view-type implementation details. But whatever, not as big a deal.

(Edit: clarification; Foo is in my model, not viewmodel.)

But now I know I'm doing something wrong when I have to change my ObservableCollection<Foo> into a custom CollectionOfFoo with logic for adding blank Foo items to the end of the collection whenever the user commits a change, like in the referenced blog post. That stuff definitely doesn't belong in my model.

How can I implement such a nice UI 开发者_开发知识库for adding new items, while at the same time preserving my MVVM-ness? I was thinking maybe some kind of wrapper around my collection that implements this, but I'm not sure how to make that wrapper bind back to the model... :-S.


That stuff definitely doesn't belong in my model.

But it definitely does belong in your viewmodel. And an observable collection of viewmodel classes is what your datagrid should be bound to.

It sounds to me like (if Foo is Model class) you need to write a FooViewModel class.

Another approach to this would be to add your "new" item in another control, maybe write a form and have it appear over the top of the datagrid whenever the user elects to create a new row?


  1. If you keep talking about how "icky" it is for your models to implement IPC, you're going to incur the wrath of the anemic model crowd.
  2. There's no reason why you can't have an ICommand in your VM to create a new Foo instance for editing.


Doesn't it disturb you that ObservableCollection itself implements INotifyPropertyChanged?

Meaning - even if it were polluting ViewModel (which it isn't), it's too late to do anything about it.

0

精彩评论

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