1

解决了:

我已经通过订阅解决了这个问题row.Loaded——一旦调用了这个方法,我就可以遍历可视化树并找到DataGridCellsPresenter我需要操作的那个。

这当然是有道理的,应该更多地投资于理解 WPF :(

原始问题:

我需要DataGridCellsPresenter在将行添加到 Datagrid 时进行操作。我尝试连接到LoadingRow事件并通过 访问它e.Row,但是当事件发生时,该行尚未插入到数据网格中(因此DataGridCellsPresentere.Row可视化树中没有,e.Row也没有在 DataGrids 行中)。

据我所知,似乎没有发生任何LoadedRow事件。加载后有什么方法可以访问新添加的行吗?

PS。我尝试更新 datagrid 和 上的布局,e.Row但无济于事。

4

1 回答 1

2

您可以从它的索引中检索该行:

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

编辑此方法也可能对您有所帮助:

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;
    }
于 2013-03-12T19:20:23.940 回答