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);
}
相关推荐
人工智能AI技术5 小时前
【C#程序员入门AI】本地大模型落地:用Ollama+C#在本地运行Llama 3/Phi-3,无需云端
人工智能·c#
MyBFuture9 小时前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
LcVong10 小时前
WPF MediaPlayer获取网络视频流当前帧并展示图片完整范例
网络·wpf
有来技术10 小时前
ASP.NET Core 权限管理系统(RBAC)设计与实现|vue3-element-admin .NET 后端
vue.js·后端·c#·asp.net·.net
bugcome_com11 小时前
WPF数据绑定入门:从传统事件到5种绑定模式
wpf
张人玉12 小时前
C#WinFrom中show和ShowDialog的区别
开发语言·microsoft·c#
m0_7482331712 小时前
C#:微软的现代编程利器
开发语言·microsoft·c#
Traced back12 小时前
SQL Server数据自动清理系统最终版(C# WinForms完整源码)
数据库·c#·.net
LateFrames12 小时前
我用 WPF 做了一个 “苍蝇飞舞” 的屏保
ui·wpf