wpf datagrid通过点击单元格 获取行列索引2.0

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);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值