1
votes

As the question states really..

I like the row that is created to be selected when it has been created, as the user is likely to want to do something with that row once created.

I normally create a row using a observable Collection via a ViewModel, and once the collection is added, the ItemSource of the WPF DataGrid is refreshed.

I will post code if necessary.

However, if there is a solution to this, it can be in the view of the DataGrid, or in a MVVM. I don't really care.

Thanks for the help

1
Bind the datagrid to a SelectedItem property in your model. When you add an item in your model, make the SelectedItem that newly added item. - Silvermind

1 Answers

2
votes

First of all you will need to bind the DataGrid's SelectedItem to a property in your model. I can't remember if the default binding mode is 2 way for SelectedItem but if not, specify 2 way in your binding so that you can set it's value in your model.

When the new record is added you need to store a reference to the primary key value and then after you refresh the ItemSource you will need to locate the object that matches the stored primary key value.

For example, if you have an integer primary key:

int recordId = [value of primary key in new record]
Records = [select records from database]
GridItemSource = Records;
SelectedItem = Records.Where(x => x.RecordId == recordId).FirstOrDefault();

If you are using a primary key which consists of an identity column you will need to obtain the new id just after inserting the record.