Search code examples
c#uielementcollection

children of object


I have a function that is supposed to return a UIElementCollection. The function takes in a UIElement that has the children property (i.e. stackpanel, grid, etc.) but does not know which UIElement it is, so I store it into a general object.

public UIElementCollection retCol (object givenObject){
...
}

I want to return the children of the givenObject, but I can't find a way to do so besides casting givenObject as a stackpanel or grid.

Is there a way I can get the children property of the givenObject?


Solution

  • StackPanel and Grid both inherit from Panel, so you could change your method to:

    public UIElementCollection retCol (Panel givenObject){
        return givenObject.Children;
    }
    

    Or if you want to make it available to ALL UIElement types you could make it more general and check the type in the function:

    public UIElementCollection retCol (UIElement givenObject){
        if(givenObject is Panel)
            return ((Panel)givenObject).Children;
        else if(givenObject is SomeOtherContainer)
            return ((SomeOtherContainer)givenObject).Children;
    
        else
            return null;
    }