2021年1月22日星期五

Get all Controls of a Type, including nested containers

I have a winforms project with a multi-level container setup in place. As in, I have a set of Panels on the top layer, each of those Panels has another set of Panels nested within them, and each of those sub-panels have a set of Controls (TextBoxes, CheckBoxes, etc.) in each one.

What I want is to be able to retrieve Controls of a certain type, given only the top level Panel. For example, one set of this using the names in my project would be MainPanelTruck which has a PanelTruckCheck Panel under it, which itself has 8 CheckBox nested in it. I want to be able to retrieve those 8 CheckBox given just MainPanelTruck. Here's an image of a section of the Panel structure for reference.

I have been trying to get OfType<>() to work but as far as I can tell, it only searches among the next level down, so when I search for CheckBox using it, I get nothing as a result, because it only looks at the sub-panels.

This would be a lot easier if the Find method in ControlCollection allowed for a predicate or condition instead of a specific string as key, because it has the searchAllChildren bool which would be very handy here.

I can think of many ways I can get the items I want here, but none of them feel particularly elegant, which is what I'm seeking here. Thanks :)

https://stackoverflow.com/questions/65855045/get-all-controls-of-a-type-including-nested-containers January 23, 2021 at 10:08AM

没有评论:

发表评论