简体   繁体   中英

Add new row immediately upon adding new item

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:

初始点

This is after double clicking the blank line and editing:

编辑

When I finish editing, a new blank line appears:

新的空行

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

编辑时的新空白行

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.

I've found a solution. Probably you might want to persist the cell editing focus so you can use dataGrid.CommitEdit(DataGridEditingUnit.Row, false );

Take a look here:

Add blank row to WPF DataGrid right after new item has been added

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM