C# 每次单击“保存”按钮时,Datagrid都会插入/添加新行
我有一个按钮(保存),每次单击它,我的datagrid都会添加新行,所以我必须再次单击,这次是从datagrid保存记录。 是因为在我的代码背后我有这样一个:C# 每次单击“保存”按钮时,Datagrid都会插入/添加新行,c#,wpf,datagrid,C#,Wpf,Datagrid,我有一个按钮(保存),每次单击它,我的datagrid都会添加新行,所以我必须再次单击,这次是从datagrid保存记录。 是因为在我的代码背后我有这样一个: private void uxItemBatchDetails_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { if (uxItemBatchDetails.Items.CurrentPosition == (uxItemBa
private void uxItemBatchDetails_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
if (uxItemBatchDetails.Items.CurrentPosition == (uxItemBatchDetails.Items.Count - 1))
(this.DataContext as ItemBatchViewModel).NewRow();
}
方法NewRow()只是在我的datagrid上插入另一行:
public void NewRow()
{
int rowIndex = 1;
if (ItemBatchDetails.Count > 0)
rowIndex = ItemBatchDetails.Max(i => i.RowIndex + 1);
ItemBatchDetails.Insert(ItemBatchDetails.Count, new ItemBatchDetailViewModel(rowIndex));
}
对于我的XAML:
<Button Content="SAVE"
Grid.Column="1"
Grid.Row="1"
Width="80"
Background="#FF930936"
Foreground="White"
Command="{Binding SaveCommand}"/>
我遗漏了什么吗?通过将网格绑定到ViewModel中的ObservableCollection,然后将项目添加到ObservableCollection,您可以轻松实现此功能(为此,您必须使用“添加行”按钮)!而不是尝试在NewRow方法后面的代码中添加行 这样做: 1.将视图绑定到ViewModel(将视图的datacontext设置为ViewModel) 2.在ViewModel上进行一次ObservableCollection(这将是您的列表,即实际数据) 3.在AddRowButton命令处理程序中,向datagrid添加一个空项。 4.现在用户可以在新行中输入一些记录。 5.在save按钮中,只需将ObservableCollection数据保存到您想要保存的位置 另外,您也可以在不使用“添加新行”按钮的情况下实现这一点,但这有点棘手