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

WPF中如何从DataGridCellInfo获取Item的Name字段值?

WPF DataGrid获取Item中Name字段的正确方法

问题出在DataGridCellInfo.Item的类型是object,直接访问Name或者用索引器会因为类型不匹配失败,得先把它转换成你的实体类型,下面是几种可行的方式:

  • 强转成实体类(推荐,有编译检查)
    假设你的数据项是Project类(替换成你实际的实体类型):
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) {
    if (ProjectsDatagrid.SelectedCells.Count == 0) return;
    
    var selected = ProjectsDatagrid.SelectedCells[0];
    // 方式1:as关键字加空判断
    var project = selected.Item as Project;
    if (project != null)
    {
        var foo = project.Name;
        // 这里使用foo
    }

    // 方式2:C#7+模式匹配(更简洁)
    if (selected.Item is Project project2)
    {
        var foo2 = project2.Name;
        // 这里使用foo2
    }
}
  • 反射获取(适用于不知道具体实体类型的场景)
    如果没法确定Item的具体类型,可以用反射读取属性值:
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) {
    if (ProjectsDatagrid.SelectedCells.Count == 0) return;
    
    var selected = ProjectsDatagrid.SelectedCells[0];
    var nameProp = selected.Item.GetType().GetProperty("Name");
    if (nameProp != null)
    {
        var foo = nameProp.GetValue(selected.Item)?.ToString();
        // 这里使用foo
    }
}
  • 动态类型(不推荐,无编译检查)
    用dynamic跳过编译类型检查,但运行时如果Item没有Name属性会报错:
private void ProjectsDatagrid_SelectionChanged(object sender, MouseButtonEventArgs e) {
    if (ProjectsDatagrid.SelectedCells.Count == 0) return;
    
    var selected = ProjectsDatagrid.SelectedCells[0];
    dynamic item = selected.Item;
    var foo = item.Name;
    // 这里使用foo
}

另外注意:一定要先判断SelectedCells的数量大于0,避免索引越界报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:27:09