使用DevExpress时如何实现grid control仅编辑当前选中单行
DevExpress GridControl 状态切换与单行编辑限制实现方案
1. 菜单点击展示对应按钮实现逻辑
- 所有关联操作按钮默认将
Visible属性设置为false - 给菜单控件绑定
Click(WinForm)/Command(WPF)触发事件,点击指定菜单时仅将对应按钮的Visible属性设为true,点击其他菜单时隐藏非对应按钮即可
2. 控件点击启用+单行编辑限制实现
核心逻辑说明
默认禁用状态下先捕获GridControl内部点击事件启用控件,再通过GridView/TableView的编辑器触发事件拦截非选中行的编辑权限,无需全局禁用其他行。
WinForm 平台代码示例
步骤1:点击控件时自动启用
给GridControl绑定MouseDown事件:
private void gridControl1_MouseDown(object sender, MouseEventArgs e) { if (gridControl1.Enabled) return; gridControl1.Enabled = true; // 选中点击位置对应的行 GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Location); if (hitInfo.InRow) { gridView1.FocusedRowHandle = hitInfo.RowHandle; } }
步骤2:限制仅选中行可编辑
给GridView绑定ShowingEditor事件:
private void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e) { GridView currentView = sender as GridView; // 非选中行直接取消编辑权限 if (currentView.FocusedRowHandle != currentView.SelectedRows[0]) { e.Cancel = true; } }
可选:切换选中行时自动关闭上一行编辑状态
绑定GridView的FocusedRowChanged事件:
private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e) { gridView1.CloseEditor(); }
WPF 平台代码示例
步骤1:点击控件时自动启用
给GridControl绑定PreviewMouseDown事件:
private void gridControl_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (gridControl.IsEnabled) return; gridControl.IsEnabled = true; // 选中点击位置对应的行 TableViewHitInfo hitInfo = tableView.CalcHitInfo((DependencyObject)e.OriginalSource); if (hitInfo.InRow) { gridControl.CurrentItem = hitInfo.Row; } }
步骤2:限制仅选中行可编辑
给TableView绑定ShowingEditor事件:
private void tableView_ShowingEditor(object sender, ShowingEditorEventArgs e) { // 非选中行直接取消编辑权限 if (e.Row != gridControl.SelectedItem) { e.Cancel = true; } }
可选优化项
- 如需离开GridControl后自动恢复禁用状态,可绑定
LostFocus事件将GridControl重新设为禁用,同时隐藏所有关联操作按钮 - 如需进一步限制仅指定列可编辑,可在
ShowingEditor事件中额外判断列的FieldName属性,符合规则才允许编辑
内容的提问来源于stack exchange,提问作者Ronald López
相关产品推荐
相关产品推荐

