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