WPF DataGrid - Event for New Rows?

前端 未结 7 1923
梦谈多话
梦谈多话 2020-12-06 17:13

I\'m using the WPF DataGrid (.Net 3.5 SP 1 version from the Toolkit)

What event can I subscribe to, to detect when a new row is added?

7条回答
  •  粉色の甜心
    2020-12-06 17:48

    I'm adding this because I've just spent close to 2 hours trying to work out how to get the DataGrid to add a new row when you are bound to a collection of view models and you need to control the construction of those view models.

    So the setup is that you have an ObservableCollection that is bound to the ItemsSource of your DataGrid. You need to create MyViewModel yourself in the view model layer.

    This is how the DataGrid appears to function when it adds a row automatically:

    1. When it creates that blank row at the bottom it creates a new instance of MyViewModel it will bind to the row by calling the default constructor on the type. Who knows why it does this, but if MyViewModel does not have a default constructor it will just fail to show that blank row. This is probably the place that you are stuck, because you don't have a default constructor, because you need to create the object yourself. Unfortunately you are going to need to go and add one. Again note that if the element type is an interface this is doomed to failure. The element type of the collection must be a concrete class with a default constructor.
    2. Now it waits until the user goes to edit the row, at which point it starts the add proper.
    3. It raises the AddingNewItem: this is where you can intercept the add operation and switch out the default constructor created instance it has created with your own instance. The AddingNewItemEventArgs.NewItem has a setter and you can swap the current item for your own.

提交回复
热议问题