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

WPF(C#) 点击DataGrid单元格时获取对应值的实现方法咨询

WPF DataGrid点击单元格获取值实现方案

1. XAML代码修改

找到现有代码中的DataGrid节点,添加选中规则配置和事件绑定:

<DataGrid x:Name="Test_grid" 
          SelectionUnit="Cell"
          SelectionMode="Single"
          SelectedCellsChanged="Test_grid_SelectedCellsChanged">
</DataGrid>

参数说明:

  • SelectionUnit="Cell" 指定DataGrid的选中单位为单元格,而非整行
  • SelectionMode="Single" 限制一次仅能选中一个单元格,符合常规点击取值需求
  • SelectedCellsChanged 为单元格选中变化事件,点击单元格时会自动触发

2. 后台C#代码修改

首先在cs文件顶部添加反射所需的命名空间引用:

using System.Reflection;

之后在ToolWindow1Control类中添加事件处理方法:

private void Test_grid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    // 无选中单元格直接返回
    if (Test_grid.SelectedCells.Count == 0) 
        return;
    
    var selectedCell = Test_grid.SelectedCells[0];
    // 空列或空数据直接返回
    if (selectedCell.Column == null || selectedCell.Item == null) 
        return;

    // 获取当前单元格绑定的属性名称
    string bindingPath = (selectedCell.Column as DataGridBoundColumn)?.Binding.Path.Path;
    if (string.IsNullOrEmpty(bindingPath)) 
        return;

    // 获取当前行绑定的实体对象,自动兼容User/User2/User3任意类型
    object dataItem = selectedCell.Item;
    
    // 通过反射读取对应属性的值
    PropertyInfo propertyInfo = dataItem.GetType().GetProperty(bindingPath);
    if (propertyInfo == null) 
        return;
    
    object cellValue = propertyInfo.GetValue(dataItem, null);
    
    // 可按需处理拿到的单元格值,示例为弹窗展示
    MessageBox.Show($"选中单元格的值:{cellValue?.ToString() ?? "空值"}");
}

方案说明

本方案无需修改现有数据源绑定逻辑,无论DataGrid绑定的是User、User2还是User3类型的集合,都能自动识别并返回点击单元格的取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:06:00