How to Get Children of a Wpf Container by Type

How to get children of a WPF container by type?

This extension method will search recursively for child elements of the desired type:

public static T GetChildOfType<T>(this DependencyObject depObj) 
where T : DependencyObject
{
if (depObj == null) return null;

for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);

var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}

So using that you can ask for MyContainer.GetChildOfType<ComboBox>().

Finding ALL child controls WPF

You can use these.

 public static List<T> GetLogicalChildCollection<T>(this DependencyObject parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent, 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);
}
}
}

You can get child button controls in RootGrid f.e like that:

 List<Button> button = RootGrid.GetLogicalChildCollection<Button>();

Find all controls in WPF Window by type

This should do the trick:

public static IEnumerable<T> FindVisualChilds<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null) yield return (T)Enumerable.Empty<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i);
if (ithChild == null) continue;
if (ithChild is T t) yield return t;
foreach (T childOfChild in FindVisualChilds<T>(ithChild)) yield return childOfChild;
}
}

then you enumerate over the controls like so

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}

How do I get children of a component 2 layers deep in a WPF app?

addEmployees.Children.OfType<Grid>() gives you an IEnumerable of Grid, not a single Grid.

So we can't just "dot" them out. Assuming every list of Grid has a number of TextBox children, we have to flatten them out with LINQ SelectMany.

This is how SelectMany works. You have a list of Grid, and each Grid has a list of TextBox.

Grid1
TextBox1
TextBox2
Grid2
TextBox3
Grid3
TextBox4
TextBox5

We can use SelectMany to turn them into

TextBox1
TextBox2
TextBox3
TextBox4
TextBox5

Here's my attempt at your code:

private IEnumerable<TextBox> addEmployeesTB = addEmployees.Children.OfType<Grid>()
.SelectMany(grid => grid.Children.OfType<TextBox>())
.ToList();

It should look like this:
Sample Image

Here is LINQ SelectMany documentation.

Please let me know if it works.

How to find WPF expander children programmatically?

Cast the Content property:

Grid grid = expander.Content as Grid;

How can I find WPF controls by name or type?

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.

/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found,
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;

T foundChild = null;

int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);

// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}

return foundChild;
}

Call it like this:

TextBox foundTextBox = 
UIHelper.FindChild<TextBox>(Application.Current.MainWindow, "myTextBoxName");

Note Application.Current.MainWindow can be any parent window.

How do I get children of the a parent element

Use the VisualTreeHelper.GetChild method of class

for(var i = 0; i < VisualTreeHelper.GetChildCount(element); i++)
{
var child = VisualTreeHelper.GetChild(element, i);
...
}

An example is also available on that page.

Get Children from ListBox can't get children that haven't been viewed

Those visual tree walking methods floating around all over the place are a plague. You should almost never need any of that.

Just bind the ItemsSource to a list of objects containing properties for the CheckBoxes, create a data template (ItemTemplate) and bind that property to the CheckBox. In code just iterate over the collection bound to ItemsSource and set the porperty.



Related Topics



Leave a reply



Submit