Reputation: 2240
I have ObservableCollection<IInterface>
which is binded to DataGrid.
IInterface is interface.
I want to add new row clearly for user (without add button). I've added CanUserAddRows="true"
but it works only when dataGrid is binded on ObservableCollection<MyClass>
.
How can I programmatically create new object for new row?
Upvotes: 1
Views: 1536
Reputation: 2295
I've recently had the same issue. I've posted a solution in my blog: Enable inline adding of records for view models with non-default constructors/interfaces
It basically involves creating a custom ListCollectionView (can be done similarly for the others) and binding the grid to that view. The custom view has a factory method used to create the rows as the default implementation in ListCollectionView doesn't support adding rows for interfaces or classes which do not have a default constructor.
Note that even if you do not use a CollectionView in your MVVM view model, but a regular list or an IBindingList, WPF will create a specific collection view for you. See more details WPF’s CollectionViewSource
Upvotes: 1
Reputation: 52300
To answer your question: "programmatically" you can add by just adding/inserting an object into your ObservableCollection
- but I think you want the automatic-adding feature you describe earlier.
The problem is that, the framework cannot know how to create an instance of your Interface - it only knows how to create types with default-constructors. So you have to change your ObserveableCollection using a concrete type or you cannot use the automatic feature and have to add the object in code-behind.
Upvotes: 2