R – Silverlight MVVM: how to avoid polluting the model while still implementing “add new item” for the datagrid

data-bindingmvvmsilverlight

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.

Best Answer

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?

Related Topic