I need to search a WPF control hierarchy for controls that match a given name or type. How can I do this?
Wpf – How to find WPF controls by name or type
controlsfindwpf
Related Topic
- Bash – How to exclude all “permission denied” messages from “find”
- Wpf – How to bind inverse boolean properties in WPF
- C# – How to get a TextBox to only accept numeric input in WPF
- C# – Metadata file ‘.dll’ could not be found
- Linux – How to exclude a directory in find . command
- Linux – How to find all files containing specific text on Linux
Best Answer
I combined the template format used by John Myczek and Tri Q's algorithm above to create a findChild Algorithm that can be used on any parent. Keep in mind that recursively searching a tree downwards could be a lengthy process. I've only spot-checked this on a WPF application, please comment on any errors you might find and I'll correct my code.
WPF Snoop is a useful tool in looking at the visual tree - I'd strongly recommend using it while testing or using this algorithm to check your work.
There is a small error in Tri Q's Algorithm. After the child is found, if childrenCount is > 1 and we iterate again we can overwrite the properly found child. Therefore I added a
if (foundChild != null) break;
into my code to deal with this condition.Call it like this:
Note
Application.Current.MainWindow
can be any parent window.