WPF Controls Lists
Using extensions to provide a similar "Winforms.Controls" collection functionality. When implementing generics with System.Windows.Window extensions the VS2013 compiler starts throwing random exceptions, so following is using a static wrapper and each control type has to separated. On tested using VS2013..
Source
public static class WPFWindowExtensions
{
public static string NameSpace(this Window window)
{
Type myType = window.GetType();
return myType.Namespace;
}
public static List<Button> ToListButtonControls(this Window window)
{
return WindowControls.GetCollection<Button>(window);
}
public static List<Label> ToListLabelControls(this Window window)
{
return WindowControls.GetCollection<Label>(window);
}
public static List<TextBox> ToListTextBoxControls(this Window window)
{
return WindowControls.GetCollection<TextBox>(window);
}
public static List<Grid> ToListGridControls(this Window window)
{
return WindowControls.GetCollection<Grid>(window);
}
public static List<StackPanel> ToListStackPanelControls(this Window window)
{
return WindowControls.GetCollection<StackPanel>(window);
}
}
public static class WindowControls
{
public static List<T> GetCollection<T>(object parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent as DependencyObject, logicalCollection);
return logicalCollection;
}
private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
{
IEnumerable children = LogicalTreeHelper.GetChildren(parent);
foreach (object child in children)
{
if (child is DependencyObject)
{
DependencyObject depChild = child as DependencyObject;
if (child is T)
{
logicalCollection.Add(child as T);
}
GetLogicalChildCollection(depChild, logicalCollection);
}
}
}
}
Example
List<System.Windows.Controls.TextBox> textboxes = this.ToListTextBoxControls();
this.ToListButtonControls()
this.ToListGridControls
this.ToListLabelControls
this.ToListTextBoxControls
this.ToListStackPanelControls