添加新项目后立即添加新行 [英] Add new row immediately upon adding new item

查看:82
本文介绍了添加新项目后立即添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据网格:

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() { }
}

datagrid的默认行为是从底部的新空行开始。当我开始编辑该行的任何属性时,将创建一个新的Thing并将其添加到Things集合中。但是,直到我完成编辑(即按Enter键或选择新的行/列)后,才会显示新的空白行。有一种方法(最好是不违反MVVM的方法)在我开始编辑后立即显示此新空白行?

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 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):

推荐答案

要获得所需的行为,您需要将事件挂接到datagrid的 PreparingCellForEdit ,只要单元格进入编辑模式就会触发该事件。

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.

此事件之后,您可以检查是否存在下一行(当前单元格索引+ 1),如果不存在,则继续创建该行。

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.

例如, PreparingCellForEdit 事件处理程序,只要最后一行开始编辑事件,这就会添加一个新项(并导致新行)。 / p>



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());
}

由于要绑定到集合,因此必须添加一个将新项目添加到集合中,而不是将新项目直接添加到数据网格中。由于您使用的是 ObservableCollection ,因此它应该自动更新以反映新行。

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.

这篇关于添加新项目后立即添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆