DevExpress Xtra Grid如何实现勾选复选框后激活Lookup Edit功能
DevExpress XtraGrid 联动控制LookupEdit列可编辑状态实现方案
前置准备
首先你需要先在绑定的人员模型中新增国家存储字段,比如命名为SelectedCountry,类型和LookupEdit的ValueMember类型保持一致即可。之后完成Grid基础列配置:
- 原有
ILiveInEurope列保留CheckEdit编辑器配置 - 新增国家列指定LookupEdit为内置编辑器,提前绑定欧洲国家数据源、配置好DisplayMember和ValueMember
核心逻辑实现
1. 控制国家列编辑权限
绑定GridView的ShowingEditor事件,该事件会在单元格进入编辑状态前触发,判断当前行是否勾选了居住在欧洲,未勾选则直接禁止进入编辑状态:
private void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e) { GridView currentView = sender as GridView; // 仅拦截国家列的编辑请求 if (currentView.FocusedColumn.FieldName == nameof(人员模型.SelectedCountry)) { bool isLiveInEu = Convert.ToBoolean(currentView.GetFocusedRowCellValue(nameof(人员模型.ILiveInEurope))); if (!isLiveInEu) { e.Cancel = true; } } }
2. 取消勾选时自动清空国家值
绑定GridView的CellValueChanged事件,监听ILiveInEurope字段的变化,当用户取消勾选时直接清空当前行的国家字段值:
private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { GridView currentView = sender as GridView; // 仅处理居住在欧洲字段的变更 if (e.Column.FieldName == nameof(人员模型.ILiveInEurope)) { bool checkValue = Convert.ToBoolean(e.Value); if (!checkValue) { currentView.SetRowCellValue(e.RowHandle, nameof(人员模型.SelectedCountry), null); currentView.RefreshRow(e.RowHandle); } } }
3. 可选优化:禁用状态视觉提示
如果需要让未勾选时国家列直接显示为灰的禁用状态,避免用户点击后才知道不可编辑,可以绑定CustomDrawCell事件修改单元格样式:
private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { GridView currentView = sender as GridView; if (e.Column.FieldName == nameof(人员模型.SelectedCountry)) { bool isLiveInEu = Convert.ToBoolean(currentView.GetRowCellValue(e.RowHandle, nameof(人员模型.ILiveInEurope))); if (!isLiveInEu) { e.Appearance.BackColor = SystemColors.Control; e.Appearance.ForeColor = SystemColors.GrayText; } } }
内容的提问来源于stack exchange,提问作者erbeen
相关产品推荐
相关产品推荐

