Remove specific object instance from Grid.Children

2019-08-17 09:32发布

I have a List<T> with some UserControls. On the main window there is a Grid and some of the UserControls will be added to Grid.Children. Now I would like to be able to remove specific UserControls from this Grid e.g. I would like to do something like this

layoutRoot.Children.Remove(controlList[1]);

Is this possible? I only know FindName() and FindResource() but all the UserControls don't have names so that I can't use these methods :(

Thanks in advance!

标签: c# wpf grid
1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-17 10:22

just an idea to get you started, if you know the type of your user control, you can use methods like this:

static T FindVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        var visual = (Visual)VisualTreeHelper.GetChild(parent, i);

        child = visual as T;
        if (child == null)
            child = FindVisualChild<T>(visual);
        if (child != null)
            break;
    }
    return child;
}
查看更多
登录 后发表回答