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);
}
相关推荐
阿翰8 分钟前
自动 GitHub Readme 20 种语言翻译平台 - OpenAiTx 开源免费
c#·.net
枫叶kx4 小时前
1Panel运行的.net程序无法读取系统字体(因为使用了docker)
c#
军训猫猫头9 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
不爱写代码的玉子11 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
明耀13 小时前
WPF DataGrid 默认显示行号
wpf
开开心心就好14 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
一名用户15 小时前
unity实现自定义粒子系统
c#·unity3d·游戏开发
lph197217 小时前
wpf的converter
wpf
fyifei055817 小时前
WPF学习PropertyChanged
wpf
钢铁男儿17 小时前
C# 类和继承(扩展方法)
java·servlet·c#