我正在尝试从用户在DataGrid上选择的单元格中提取值。我将需要为多个DataGrids执行此操作,但目前我无法获取“getDataGridCellMethod”方法来返回一个值,因为我不断收到错误“名称Dec在当前上下文中不存在”
//第一个网格选择更改事件
public void grid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
decimal Dec = getDataGridCell.returnCellValue(sender, e);
}
//返回所选单元格值的方法
public static class getDataGridCell
{
public static decimal returnCellValue(object sender, SelectionChangedEventArgs e)
{
DataGrid grid = sender as DataGrid;
if (e.AddedItems != null && e.AddedItems.Count > 0)
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
if (cell != null)
{
Decimal Dec = Convert.ToDecimal(((TextBlock)cell.Content).Text);
}
return Dec;
}
}
}
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null) child = GetVisualChild<T>(v);
if (child != null) break;
}
return child;
}
}
}
}
如果我将returnCellValue方法嵌套在事件中并直接在if语句中使用Dec的值,那么这是有效的,但我宁愿不必为每个DataGrid执行此操作