wpf datagrid通过点击单元格 获取行列索引2.0

csharp 复制代码
private void DataGrid_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    var dataGrid = sender as DataGrid;
    // 获取点击的位置
    var mousePosition = e.GetPosition(dataGrid);
    var hit = dataGrid.InputHitTest(mousePosition) as FrameworkElement;

    if (hit != null)
    {
        // 获取点击的单元格
        DataGridCell cell = FindParent<DataGridCell>(hit);
        if (cell != null)
        {
            DataGridRow row = FindParent<DataGridRow>(cell);
            // 获取行索引
            int rowIndex = row.GetIndex();
            //获取列索引
            int columnIndex = cell.Column.DisplayIndex;

            Console.WriteLine($"行索引: {rowIndex}, 列索引: {columnIndex}");
         
            
            // 获取当前单元格的内容
            // var currentValue = cell.Content.ToString();  
            
            // 修改数据源中的值
            dynamic rowItem = dataGrid.Items[rowIndex];
            var propertyName = cell.Column.SortMemberPath; // 获取绑定的属性名
            rowItem.GetType().GetProperty(propertyName).SetValue(rowItem, "aaa");
        }
    }
}

// 辅助方法:找到指定类型的父级元素
private T FindParent<T>(DependencyObject child) where T : DependencyObject
{
    DependencyObject parentObject = VisualTreeHelper.GetParent(child);
    if (parentObject == null) return null;

    T parent = parentObject as T;
    return parent ?? FindParent<T>(parentObject);
}
相关推荐
2501_930707785 小时前
使用C#代码更改 PowerPoint 幻灯片大小
开发语言·c#·powerpoint
Z_W_H_6 小时前
【C#】C#中值类型和引用类型参数传递的区别
开发语言·c#
用户8356290780517 小时前
使用 C# 高效解析 PDF 文档:文本与表格提取实战指南
后端·c#
rit84324998 小时前
C#实现的远程控制系统
前端·javascript·c#
wuguan_9 小时前
C#中的静态成员、常量和只读变量
开发语言·c#
秋雨雁南飞9 小时前
C# SignalR 添加Swagger
c#·swagger·signalr
张人玉9 小时前
C# 与西门子 PLC 通信:地址相关核心知识点
开发语言·microsoft·c#·plc
Yuuuuuuu10 小时前
WPF基于Canvas绘制多边形ROI
c#
缺点内向10 小时前
如何在 C# 中重命名 Excel 工作表并设置标签颜色
开发语言·c#·excel
a努力。11 小时前
网易Java面试被问:偏向锁在什么场景下反而降低性能?如何关闭?
java·开发语言·后端·面试·架构·c#