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);
}
相关推荐
Charles_go11 小时前
C#13、什么是部分类
开发语言·c#
ghie909015 小时前
C#语言中使用“using“关键字的介绍
开发语言·c#
csdn_wuwt16 小时前
有C#可用的开源的地图吗?
后端·c#·gis·map·开发·设计·地图
6极地诈唬16 小时前
【C#-sqlSugar-sqlite】在Windows从源码编译构建System.Data.SQLite.dll的方法
windows·sqlite·c#
我只有一台windows电脑16 小时前
C# 对多个任务进行符合管理
c#
数据的世界0117 小时前
JAVA和C#的语法对比
java·windows·c#
Macbethad20 小时前
如何用WPF做工控设置界面
java·开发语言·wpf
csdn_aspnet20 小时前
WPF 做一个简单的电子签名板(一)
c#·wpf
玖笙&20 小时前
✨WPF编程进阶【7.2】:动画类型(附源码)
c++·c#·wpf·visual studio
她说彩礼65万21 小时前
C# 容器实例生命周期
开发语言·c#