Did You Know That… there are numerous ways to find an object inside a Silverlight control

Is very common to need to access a Silverlight element programmatically. There are numerous ways to do so. Assuming you have named your element as shown here

<Rectangle Name="myRect"
           Stroke="Black" />

One very simple way to access this rectangle from the handleLoad function is by using getItem() and indexing into the children collection of the root element

this.rect = rootElement.children.getItem(0);

An alternative and more general approach is to use findName(),  which you can also call on any element, including the root element

this.rect2 = rootElement.FindName("myRect");
this.rect2.Fill = "Red";

Note this quote from the documentation: the object you are searching for does not have to be a direct descendant of the object that invokes the findName method.

In addition, you can call FindName() on the plugin's content sub-object

var rect3 = plugIn.content.FindName("myRect");
rect3["Canvas.Left"] = 300;

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.