Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: Find all controls of type in layout

I'm looking for a reliable method to build a list of controls of <Type> contained in a specific <Panel> derived control - this includes those that are direct children, and those which are children of children and so on.

The most obvious way was to just do it recursively:
Add to list any children of this control of <Type>, then repeat function for any child of this control which is a <Panel> or descendant.

However I'm concerned that this won't find all controls in the tree - any ContentControl could also contain of a control of <Type>, as could HeaderedContentControl or any other similar control with one or more child/content attributes.

Is there any means of executing a search against the actual layout tree, so that any instance of a specific type of control contained without a specific parent can be found?

like image 894
David Avatar asked Nov 23 '09 16:11

David


2 Answers

Here is a fairly naive extension method:-

public static class VisualTreeEnumeration
{
   public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
   {
     int count = VisualTreeHelper.GetChildrenCount(root);
     for (int i=0; i < count; i++)
     {
       var child = VisualTreeHelper.GetChild(root, i);
       yield return child;
       foreach (var descendent in Descendents(child))
         yield return descendent;
     }
   }
}

This approach does have the draw back that it assumes no changes happen in the tree membership while its in progress. This could be mitigated in use by using a ToList().

Now you can effect your requirements using LINQ:-

 var qryAllButtons = myPanel.Descendents().OfType<Button>();
like image 192
AnthonyWJones Avatar answered Sep 29 '22 14:09

AnthonyWJones


Let's say you want to find comboboxes inside a userControl which starts with a GRID and has nested grids, stackpanels, canvas etc. containing comboboxes

  1. Imports System.Windows.Controls.Primitives (or Using for C#)
  2. Dim ListOfComboBoxes = MAINGRID.GetVisualDescendants.OfType(Of ComboBox)

That's it...

like image 30
Otto Kanellis Avatar answered Sep 29 '22 16:09

Otto Kanellis