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);
}
相关推荐
zimoyin8 小时前
在 C# 里嵌入 JavaScript:用 Jint 做可热更新的自动化脚本(从入门到踩坑)
javascript·c#·自动化
小羊没烦恼!10 小时前
异步编程:线程概述及使用
java·开发语言·mysql·算法·c#
c#上位机12 小时前
C#上位机项目实战——exe项目调试更改dll中源代码
开发语言·c#
淡海水13 小时前
06-02-源码-增量标记算法实现
算法·unity·c#·gc
淡海水14 小时前
06-01-源码-Incremental GC总览与设计
unity·c#·gc
江沉晚呤时17 小时前
零依赖的代价与自由:我用 C# 自研了一套 Office 读写库
开发语言·c#
nap11718 小时前
WPF 中常用的 LINQ 语句
wpf
zimoyin19 小时前
Windows 控件获取全攻略:Win32 / UIA / MSAA + 鼠标拾取与点击关联(C# 实战)
c#·自动化
小羊没烦恼!1 天前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
昂好的day1 天前
VisionMaster 通信模块实战(上):Modbus、TCP 收发、协议组装解析
开发语言·网络·网络协议·tcp/ip·c#