I have the Following Method used to walk the Visual Tree to find all objects of a Type:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
The Problem is the Type is a string value stored in a veriable. Using the Above works fine when passed a Type like the following:
var x = FindVisualChildren<TextBox>(this);
However in my case TextBox is a string stored in a variable we will call item. So I want to do something like this:
var item = "TextBox";
var x = FindVisualChildren<item>(this);
But Item is not a type. So what is the best way to get the Type of the Sting Variable so it can be passed to my method. The Variable will be a TextBox, TextBlock, Grid, StackPanel, DockPanel, or TabControl. Right now I have everything in a Switch Statement and it is working but would like a cleaner way to do the same thing.