我已经通过订阅row.Loaded
解决了这个问题 - 一旦调用此方法,我就可以遍历可视树并找到我需要操作的DataGridCellsPresenter
。
当然有意义的是,应该投入更多地了解WPF :(
当一行已添加到Datagrid中时,我需要操纵DataGridCellsPresenter
。我尝试挂钩LoadingRow
事件并通过e.Row
访问它,但是当事件发生时,该行尚未插入数据网格中(因此DataGridCellsPresenter
中没有e.Row
可视化树和e.Row
不在DataGrids行中。)
据我所知,似乎没有LoadedRow
事件。有什么办法可以在加载后访问新添加的行吗?
PS。我尝试更新datagrid和e.Row
上的布局,但没有用。
答案 0 :(得分:1)
您可以从索引中检索行:
//found this on SO, I don't remember who, credit to original coder
public static DataGridRow GetRow(this DataGrid grid, int index)
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// May be virtualized, bring into view and try again.
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
或者通过它的数据项:
var row= DataGrid.ItemContainerGenerator.ContainerFromItem(youritem);
EDIT 这种方法也可能对您有所帮助:
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}