Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new row immediately upon adding new item

Tags:

c#

wpf

datagrid

I have a datagrid like this:

<DataGrid
    ItemsSource="{Binding Things}" 
    AutoGenerateColumns="False">

    <DataGrid.Columns>
        <DataGridTextColumn Header="Whatever" Binding="{Binding Blah}" />
    </DataGrid.Columns>     
</DataGrid>

Things and Thing look like this:

public ObservableCollection<Thing> Things { get; set; }

.

public class Thing
{
    public string Blah { get; set; }

    public Thing() { }
}

The default behavior for the datagrid is to start with a new empty line at the bottom. When I begin to edit any property of that line, a new Thing is created and added to the Things collection. However a new blank line is not displayed until I finish editing (ie press the enter button or select a new row/column). Is there a way (preferably one that doesn't violate MVVM) to make this new blank line show immediately after I begin editing?

This is the starting point:

Starting Point

This is after double clicking the blank line and editing:

Editing

When I finish editing, a new blank line appears:

New Blank Line

But here is what I want (New blank line while editing):

New Blank Line While Editing

like image 288
ConditionRacer Avatar asked Nov 02 '22 10:11

ConditionRacer


1 Answers

To get the behavior you want, you're going to need to hook up an event to the datagrid's PreparingCellForEdit, which gets fired whenever the cell goes into edit mode.

From this event, you can then check to see if the next row exists (current cell index + 1), and if it doesn't, go ahead and create it at that point.

I believe this will then create the desired effect of having the new row added as soon as you start to edit the cell.

For example, the PreparingCellForEdit event handler, this would add a new item (and result in a new row) whenever the last row starts an edit event.

DataGrid dataGrid = sender as DataGrid;

if (dataGrid == null)
{
    return; 
}

int currentRow = e.Row.GetIndex();

if (dataGrid.Items.Count - 1 <= currentRow)
{
    Things.Add(new Thing());
}

Since you're binding to a collection, you'll have to add a new item to the collection instead of adding a new item directly to the data grid. Since you're using an ObservableCollection, it should automatically update to reflect a new row.

However, this would result in you always have an extra Thing in your collection, which you may not want.

like image 93
Nathan Dace Avatar answered Nov 11 '22 07:11

Nathan Dace