You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF Telerik RadGridView单元格验证无效时按钮点击失效求助

RadGridView验证失败时Cancel按钮无法响应的解决办法

问题场景

使用Telerik RadGridView的单元格验证功能时,当单元格内容无效,窗口内所有按钮都无法响应。已在验证失败时禁用Done按钮,但Cancel按钮应始终可用——虽然它看起来可点击,但点击事件断点从未触发。尝试在BeginningEdit和CellEditEnded事件中设置btnCancel.IsEnabled = true也无效。

核心原因

RadGridView在单元格验证失败时,会锁定当前编辑单元格的焦点并拦截输入事件,即使Cancel按钮标记为IsCancel=True,也会被GridView的事件拦截机制阻止响应。此时必须先强制结束单元格的编辑状态,才能让Cancel按钮的点击事件正常触发。

解决方案

1. 修改Cancel按钮点击事件,先强制结束编辑

在Cancel按钮的点击事件中,先调用RadGridView的CancelEdit()方法结束当前编辑状态,再执行窗口关闭或取消逻辑,绕过验证失败时的事件拦截。

2. 确保Cancel按钮始终保持可用状态

在CellValidating事件中主动设置btnCancel.IsEnabled = true,避免被其他逻辑意外禁用。

代码修改示例

ButtonChooser.xaml.cs 修改

private void RadGridViewCellValidating(object sender, GridViewCellValidatingEventArgs e)
{
    e.IsValid = true;
    // 始终确保Cancel按钮可用
    btnCancel.IsEnabled = true;

    if (string.Compare(e.Cell.Column.UniqueName, "Description") == 0 && e.EditingElement is TextBox element)
    {
        if (string.IsNullOrEmpty(element.Text))
        {
            e.IsValid = false;
            e.ErrorMessage = "内容不能为空";
        }
        else if (element.Text.Length > 255)
        {
            e.IsValid = false;
            e.ErrorMessage = "内容长度不能超过255个字符";
        }

        btnDone.IsEnabled = e.IsValid;
    }
}

private void OnCancelButtonClick(object sender, RoutedEventArgs e)
{
    // 先强制结束GridView的编辑状态,绕过验证拦截
    gridSelectedControls.CancelEdit();
    // 执行你的取消逻辑,比如关闭窗口
    this.Close();
}

额外优化(可选)

如果希望点击Cancel时直接丢弃编辑内容,可在调用CancelEdit()后刷新GridView的数据源绑定,确保单元格内容回滚到编辑前的状态:

gridSelectedControls.ItemsSource = null;
gridSelectedControls.ItemsSource = SelectedControls;

内容的提问来源于stack exchange,提问作者jnpowrie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 13:13:24