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);
}
相关推荐
wkj0012 分钟前
java 和 C#操作数据库对比
java·数据库·c#
码观天工3 小时前
.NET AI Preview 2 发布:从 .NET Aspire 支持到 Qdrant 向量数据库集成,助你快速构建云原生 AI 应用
ai·c#·.net·向量数据库·aspire·qdrant
时光追逐者3 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 36 期(2025年4.21-4.27)
c#·.net·.netcore
lancoff4 小时前
(七)深入浅出WPF——深入浅出话属性
前端·c#
CHQIUU4 小时前
在 C# .NET 中驾驭 JSON:使用 Newtonsoft.Json 进行解析与 POST 请求实战
c#·json·.net
o0向阳而生0o5 小时前
27、Session有什么重⼤BUG?微软提出了什么⽅法加以解决?
c#·.net
Java Fans15 小时前
WPF使用SQLite与JSON文本文件结合存储体侧平衡数据的设计与实现
sqlite·json·wpf
code_shenbing15 小时前
WPF高级用法示例
c#·wpf·wpf高级
冰茶_15 小时前
WPF之XAML基础
microsoft·微软·c#·.net·wpf·xaml·xamarin
呼Lu噜16 小时前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf