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