你可以使用以下扩展来轻松地获取DataGrid中的选定行、所需单元格、所需行、选定行。无需被冗长的代码行吓到。最初,我从
这里受益,并根据我的问题进行了调整。
public static class DataGridHelper
{
public static T FindElementByName<T>(FrameworkElement element, string sChildName) where T : FrameworkElement
{
T childElement = null;
var nChildCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < nChildCount; i++)
{
FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
if (child == null)
continue;
if (child is T && child.Name.Equals(sChildName))
{
childElement = (T)child;
break;
}
childElement = FindElementByName<T>(child, sChildName);
if (childElement != null)
break;
}
return childElement;
}
public 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;
}
public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
if (presenter == null)
{
grid.ScrollIntoView(row, grid.Columns[column]);
presenter = GetVisualChild<DataGridCellsPresenter>(row);
}
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
return cell;
}
return null;
}
public static DataGridCell GetCell(this DataGrid grid, int row, int column)
{
DataGridRow rowContainer = grid.GetRow(row);
return grid.GetCell(rowContainer, column);
}
public static DataGridRow GetRow(this DataGrid grid, int index)
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static DataGridRow GetSelectedRow(this DataGrid grid)
{
return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}
}
只需复制并粘贴为新类。然后像这样使用它:
这是在使用上述扩展获取单元格后访问单元格内容(如按钮、文本框、组合框等)的方法。
如果您使用列或数据模板,这将非常有用。
private FrameworkElement GetComponentOfCell(int row, int column, string nameOfComponent)
{
DataGridCell cell = dgOperationList.GetCell(row, column);
return DataGridHelper.FindElementByName<FrameworkElement>(cell, nameOfComponent);
}
GetComponentOfCell(row_index, column, nameOfControl) as ComboBox;
使用以下方法来迭代遍历DataGrid:
for (int row = 0; row < dgOperationList.Items.Count - 1; row++)
{
DataGridRow dgr = dgOperationList.GetRow(row);
dgOperationList.GetCell(dgr,);
GetComponentOfCell(row,,)
}
重要提示:如果您在窗口或用户控件加载事件之前尝试使用这些扩展,即使DataGrid的itemsource已经绑定,您可能会遇到空值或对象实例异常。