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);
}
相关推荐
△曉風殘月〆6 小时前
WPF中的坐标转换
wpf
虚行6 小时前
C#上位机工程师技能清单文档
开发语言·c#
小白杨树树9 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#
Tiger_shl10 小时前
三大并发集合ConcurrentDictionary、ConcurrentBag、ConcurrentQueue
开发语言·c#
一个天蝎座 白勺 程序猿10 小时前
深度解析:通过ADO.NET驱动Kdbndp高效连接与操作Kingbase数据库
数据库·.net·wpf·kingbase·金仓数据库
时光追逐者11 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图
Vae_Mars11 小时前
WPF中的DataTemplate
wpf
Aevget11 小时前
界面控件DevExpress WPF v25.2新功能预览 - 聚焦AI功能提升
人工智能·wpf·界面控件·devexpress·ui开发·.net 10
我是唐青枫12 小时前
C#.NET FluentValidation 全面解析:优雅实现对象验证
c#·.net
YuanlongWang12 小时前
C# 设计模式——工厂模式
开发语言·设计模式·c#