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);
}
相关推荐
almighty2725 分钟前
C# ObjectListView实现树状文件夹浏览
c#·树状图·objectlistview·c#树状图·文件显示
ccut 第一混7 小时前
c# 调用basler 相机
c#·halcon·basler
TomCode先生7 小时前
c#动态树形表达式详解
开发语言·c#
上位机付工15 小时前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
土了个豆子的16 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修16 小时前
c#中public类比博图
c#·自动化
土了个豆子的19 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
somethingGoWay1 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay1 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
xiaowu0802 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式