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);
}
相关推荐
z落落1 小时前
C# ArrayList 动态集合(接口/区别/API/深浅拷贝)+ List<T> 泛型集合
开发语言·c#
游乐码1 小时前
unity基础(八)协程
游戏·unity·c#·游戏引擎
Xin_ye100861 小时前
C# 零基础到精通教程 - 第十六章:ASP.NET Core Web API——构建现代 Web 服务
开发语言·c#
z落落1 小时前
C#ArrayList 和 List<T>核心对比和数组对比
开发语言·c#·list
xiaoshuaishuai811 小时前
C# 内存管理与资源泄漏
开发语言·c#
z落落15 小时前
C#参数区别
java·算法·c#
影寂ldy15 小时前
C#随机数
开发语言·c#
雪豹阿伟16 小时前
11.C# —— 数组属性、高级方法与 Lambda 表达式
c#·上位机
唐青枫17 小时前
C#.NET YARP 服务发现实战:接入 Consul 和 Kubernetes 动态发现后端服务
c#·.net
largecode17 小时前
座机号码认证如何操作?申请热线实名名片,树立统一官方客服形象
linux·sql·华为·c#·.net·wpf·harmonyos