WPF学习笔记-BeginningEdit和CellEditEnding
BeginningEdit 在行或单元格进入编辑模式之前发生
CellEditEnding 在单元格编辑器执行或取消之前发生
<DataGrid Name="AlarmDataDG" BeginningEdit="AlarmDataDG_BeginningEdit" CellEditEnding="AlarmDataDG_CellEditEnding"/>
private void AlarmDataDG_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) { TextBlock tbl = e.Column.GetCellContent(e.Row) as TextBlock; if(tbl == null) { return; } _oldvalue = (e.Column.GetCellContent(e.Row) as TextBlock).Text; _columnName = e.Column.Header.ToString(); } private void AlarmDataDG_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { if (!(e.EditingElement is TextBox tb)) return; string newValue = tb.Text; if (AlarmDataDG.SelectedItem != null) { if (newValue != _oldvalue) { Base_Error_ListEntity model = AlarmDataDG.SelectedItem as Base_Error_ListEntity; StringBuilder strSql = new StringBuilder(); strSql.Append($"update base_error_list set "); switch (_columnName) { case "报警原因": strSql.Append($"yy = '{newValue}' "); break; case "采取措施": strSql.Append($"cqcs = '{newValue}' "); break; case "责任人": strSql.Append($"zrr = '{newValue}' "); break; } strSql.Append($"where id = '{model.Id}'"); using (var db = new FrameContext()) { int ret = db.Database.ExecuteSqlCommand(strSql.ToString()); if(ret <= 0) { MessageBox.Show("更新字段失败,请重试!", "提示", MessageBoxButton.OK); } } } } }