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.


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

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

return doList;


Partial Public Class MainPage
Inherits UserControl
Public Sub New()
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)()
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.



Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Anonymous said...

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

Anonymous said...

Nice post Suprotim Agarwal, thank you!

Rodney said...


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?