Remove specific object instance from Grid.Children?

本秂侑毒 提交于 2019-12-25 03:00:31

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/12878009/remove-specific-object-instance-from-grid-children

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!