欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > wpf datagrid通过点击单元格 获取行列索引2.0

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

2024/10/24 13:33:05 来源:https://blog.csdn.net/u014018281/article/details/141558190  浏览:    关键词: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);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com