c# - DataGrid如何获取CurrentCell的值

标签 c# .net wpf wpfdatagrid

我必须访问 DataGrid 事件单元格(周围有黑色边框的单元格)下的值。

幸运的是,DataGrid 有很多属性,例如 CurrentCell、CurrentItem SelectedCells、SelectedItem 和 SelectedItems 似乎可以为我提供我想要的数据。

但是我还没有想出如何以简单的方式访问单元格。我也改变了……

SelectionMode="Single" SelectionUnit="Cell"

...属性,但最后我不得不做这样的事情:

DataGridCellInfo cellInfo = dataGrid.CurrentCell;

if(null != cellInfo && cellInfo.IsValid)
{
    object[] array = cellInfo.Item as object[];
    if (null != array && cellInfo.Column.DisplayIndex >= 0 && cellInfo.Column.DisplayIndex < array.Length) 
    {
        object cellValue = array[cellInfo.Column.DisplayIndex];
        if (null != cellValue) 
        {
            // Here we are
        }
    }
}

在我的示例中,该行是通过包含各种对象类型的对象数组构建的。我知道我可以在 cellInfo.Column 上执行绑定(bind)(在转换之后),但这不是重点。我的问题是,如果我做错了什么,因为我无法想象像 DataGrid 这样强大的软件,如果不进行大量编码就无法为我提供所需的值。

我错过了什么,或者获取当前单元格值真的如此复杂。

更新

正如 Quartermeister 在他非常好的回答中所解释的那样,没有一个属性可以访问单元格值,这是有一个有意义的原因。此外,如果您让用户重新排列列,请注意不要像我在示例中那样使用 DisplayIndex。

最佳答案

真的有那么复杂。问题是 DataGridColumn 不一定绑定(bind)到单个值。 DataGridTemplateColumn ,例如,只有一个 DataTemplate。该模板可能使用行对象中的多个值,甚至根本不使用任何值,因此无法有效地为该单元格返回单个值。

如果该列是 DataGridBoundColumn,您可以保证只有一个值(例如 DataGridTextColumn )。正如你所说,你可以通过执行绑定(bind)来获取值。例如,您可以这样做(请注意,这不适用于使用 ElementName 或 RelativeSource 的绑定(bind),但您可能不会在 DataGridBoundColumn 中使用它们):

var cellInfo = dataGrid.CurrentCell;
if (cellInfo != null)
{
    var column = cellInfo.Column as DataGridBoundColumn;
    if (column != null)
    {
        var element = new FrameworkElement() { DataContext = cellInfo.Item };
        BindingOperations.SetBinding(element, FrameworkElement.TagProperty, column.Binding);
        var cellValue = element.Tag;
    }
}

请注意,您可能不想使用 DisplayIndex 属性,因为如果用户手动拖动列以重新排序,则可以更改该属性。

关于c# - DataGrid如何获取CurrentCell的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3272267/

相关文章:

c# - MVC 中的 session 管理

c# - 程序集Microsoft.VC90.CRT问题

WPF 绑定(bind)到自身

c# - Entity Framework - ConnectionProviderName 的更新数据库命令提示

c# - 使用 JSON.NET 的序列化字段的顺序

c# - 无法创建 Azure WebSpace

c# - 添加 OxyPlot PointAnnotation

c# - 如何将字段绑定(bind)到用户控件

WPF 将 CommandParameter 绑定(bind)到 MenuItem 中的 GridViewColumnHeader 内容

c# mvc3 razor - 模型中匹配列表项的 foreach 循环的替代方法