Find all the Silverlight Button Controls On a Page

Recently I had to recursively list all the Silverlight Button controls on a Page. I stumbled across a piece of generic code suggested by tucod. Here’s the code for your reference which recursively finds all the Buttons in the VisualTree.

C#

public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
var btns = GetButtonControls(LayoutRoot).OfType<Button>();
foreach (var btn in btns)
{
// btn.Content
}
}

IEnumerable<DependencyObject> GetButtonControls(DependencyObject root)
{
List<DependencyObject> doList = new List<DependencyObject>();
doList.Add(root);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
doList.AddRange(GetButtonControls(VisualTreeHelper.GetChild(root, i)));

return doList;
}
}

VB.NET

Partial Public Class MainPage
Inherits UserControl
Public Sub New()
InitializeComponent()
Dim btns = GetButtonControls(LayoutRoot).OfType(Of Button)()
For Each btn In btns
' btn.Content
Next btn
End Sub

Private Function
GetButtonControls(ByVal root As _
DependencyObject) As IEnumerable(Of DependencyObject)
Dim doList As New List(Of DependencyObject)()
doList.Add(root)
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(root) - 1
doList.AddRange(GetButtonControls(VisualTreeHelper.GetChild(root, i)))
Next i

Return doList
End Function
End Class

The Windows.Media.VisualTreeHelper provides utility methods to traverse object relationships.

OUTPUT

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Anonymous said...

I'm very happy that I found this solution!! Zsolt

Anonymous said...

Nice post Suprotim Agarwal, thank you!
Jesse

Rodney said...

Hi,

I ma having problems with GetChildrenCount - it returns 0 - I have to specify the exact parent element for it to work, I cant just point it at the top level element. Eg. I have a grid with a stackpanel with another grid and 2 textboxes. The textboxes will only be found if I enter their exact parent as the starting position. I want to find all textboxes on the page?