您的位置:首页 > 大数据 > 人工智能

DataGrid:Maintaining an Empty Row for the Entry of New Records

2012-06-17 18:42 309 查看
The final (and generally most user-friendly) method is to automatically maintain an empty row as the
last row in the DataGrid. The user can enter data for a new item in this row, and the DataGrid should
automatically add a new empty row once they do. Sadly, there is no built-in feature like this in the core
Silverlight DataGrid. You could add it yourself (all the source code for the DataGrid control is available in
the Silverlight Toolkit), but it’s not a great idea, as you’d be tying yourself to that particular version of the
DataGrid control, and wouldn’t be able to (easily) take advantage of new features and bug fixes in future
releases of Silverlight and the Silverlight Toolkit. You can, however, handle a number of events raised by
the DataGrid control and manage this automatically. The steps are as follows:
1. Maintain a class-level variable that will reference the new item object:
private object addRowBoundItem = null;
2. Add a new item to the bound collection before (or shortly after) binding, and
assign this item to the class-level variable. If binding the DataGrid directly to a
DomainDataSource control, you would do this in the LoadedData event of the
DomainDataSource control, like so:

DomainDataSourceView view = productDataGrid.ItemsSource as DomainDataSourceView;
addRowBoundItem = new Product();
view.Add(addRowBoundItem);
3. Handle the RowEditEnded event of the DataGrid control. If the row being
committed is the empty row item that was edited (you can get the item in the
collection that it is bound to from the DataContext property of the row), then
it’s time to add a new item to the end of the bound collection, ensure it is
visible, select it, and put it in edit mode. For example:

private void productDataGrid_RowEditEnded(object sender,
DataGridRowEditEndedEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
if (e.Row.DataContext == addRowBoundItem)
{
DomainDataSourceView view =
productDataGrid.ItemsSource as DomainDataSourceView;
addRowBoundItem = new Product();
view.Add(addRowBoundItem);
productDataGrid.SelectedItem = addRowBoundItem;

productDataGrid.CurrentColumn = productDataGrid.Columns[0];
productDataGrid.ScrollIntoView(addRowBoundItem,
productDataGrid.CurrentColumn);
productDataGrid.BeginEdit();
}
}
}

4. Remember to always delete the last item in the collection before submitting
the changes back to the server (as it will always be the item representing the
new row):
DomainDataSourceView view = productDataGrid.ItemsSource as DomainDataSourceView;
view.Remove(addRowBoundItem);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐