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

WPF Datagrid按Enter跳转下一行同列后如何自动进入单元格编辑模式

解决方案

你遇到的问题主要来自两个核心原因:一是列索引硬编码错误,二是DataGridTemplateColumn自定义模板后,默认编辑逻辑无法自动定位到单元格内的TextBox控件。

步骤1:修改PreviewKeyDown事件代码

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key is Key.Enter or Key.Return)
    {
        DataGrid grid = sender as DataGrid;
        // 校验是否已经到最后一行,避免索引越界
        if (grid.SelectedIndex + 1 >= grid.Items.Count)
        {
            e.Handled = true;
            return;
        }

        // 直接按名称获取MeasuredResult列,避免后续列顺序变动导致索引失效
        var targetColumn = grid.Columns.First(c => c.Header.ToString() == "MeasuredResult");
        // 定位到下一行的目标列
        var nextItem = grid.Items[grid.SelectedIndex + 1];
        grid.CurrentCell = new DataGridCellInfo(nextItem, targetColumn);
        grid.SelectedItem = nextItem;

        // 进入编辑模式
        grid.BeginEdit();

        // 找到单元格内的TextBox并设置焦点,可选添加选中内容逻辑方便直接输入
        if (grid.CurrentCell.Column.GetCellContent(nextItem) is TextBox textBox)
        {
            textBox.Focus();
            textBox.SelectAll();
        }

        e.Handled = true;
    }
}

步骤2:补充DataGrid配置(可选但建议)

在你的DataGrid标签上添加以下属性,提升交互稳定性:

<DataGrid 
    SelectionUnit="Cell" 
    SelectionMode="Single"
    PreviewKeyDown="DataGrid_PreviewKeyDown">
    <!-- 原有列定义保持不变 -->
</DataGrid>

优化说明

  1. 移除了不可靠的MoveFocus逻辑,直接通过索引定位下一行,不会出现焦点漂移问题
  2. 按列名获取目标列,避免后续新增/删除列后索引失效的问题
  3. 手动定位到单元格内的TextBox并设置焦点,不需要二次按回车即可直接输入
  4. 增加了最后一行的边界判断,避免索引越界报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:48:02