infolink

Wednesday, April 14, 2010

Getting a child element in Silverlight - Simple solution

I needed to get a child element of my layout root. I knew the index, but most examples out there were so confusing and way too involved for something that seemed so easy. This reminded me of a comment from a developer at Microsoft:

"If it seems too hard or way too much code, you must doing it wrong" - Trevor Fellman

You what, great advice, it turns out I found the following examples:

Get Child, Parent, or Children Objects in Silverlight:

http://www.mostlydevelopers.com/mostlydevelopers/blog/post/2009/06/17/Get-Child-Parent-or-Children-Objects-in-Silverlight.aspx

Great advice, if I didn't know the index of the object, yet I do, (Silverlight Spy is your friend)

Then I came across this:

LINQ to Visual Tree

http://www.codeproject.com/Articles/63157/LINQ-to-Visual-Tree.aspx

very neat stuff and I see myself using this in the future, but too involved for what I needed to do.

I then found this:

VisualTreeHelper Class

http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper(v=VS.95).aspx

Not this had me thinking, how can I simply call this and get my object in c# all in one simple line of code, and here is what I came up with:
ImageScroll myimagescroll;
myimagescroll = (VisualTreeHelper.GetChild(this.LayoutRoot, 7) as ImageScroll);
What this line does is exactly what i was looking for. My object IMAGESCROLL, which is index #7 in the collection(children) of the Layoutroot Grid Object.

No comments:

Post a Comment

Amazon1