在向DataGrid添加元素后获取“真实”Datarow

时间:2013-03-12 17:04:17

标签: c# .net wpf datagrid

解决:

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

当然有意义的是,应该投入更多地了解WPF :(

原始问题:

当一行已添加到Datagrid中时,我需要操纵DataGridCellsPresenter。我尝试挂钩LoadingRow事件并通过e.Row访问它,但是当事件发生时,该行尚未插入数据网格中(因此DataGridCellsPresenter中没有e.Row可视化树和e.Row不在DataGrids行中。)

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

PS。我尝试更新datagrid和e.Row上的布局,但没有用。

1 个答案:

答案 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;
    }