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);
}
相关推荐
武藤一雄1 小时前
WPF处理耗时操作的7种方法
microsoft·c#·.net·wpf
Venom841 小时前
我的 WPF Powermill 工具
wpf
武藤一雄2 小时前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
l1t3 小时前
DeepSeek总结的用 C# 构建 DuckDB 插件说明
前端·数据库·c#·插件·duckdb
iReachers4 小时前
恒盾C#混淆加密大师 1.4.5 最新2026版本发布 (附CSDN下载地址)
c#·c#混淆·c#加密·wpf加密·winform加密
历程里程碑5 小时前
43. TCP -2实现英文查中文功能
java·linux·开发语言·c++·udp·c#·排序算法
月巴月巴白勺合鸟月半5 小时前
一次PDF文件的处理(二)
pdf·c#
摆烂的少年6 小时前
Asp .net web应用程序使用VS2022调试时打开文件选择器服务自动关闭问题
c#·.net
William_cl7 小时前
C# ASP.NET Identity 授权实战:[Authorize (Roles=“Admin“)] 仅管理员访问(避坑 + 图解)
开发语言·c#·asp.net
.NET修仙日记7 小时前
构建社区照护桥梁:.NET Core3.1+MVC社区呼叫系统设计与实现
c#·毕业设计·.net·.net core·社区照护平台