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"
           Width="100"
           Height="44"
           Canvas.Left="0"
           Canvas.Top="10"
           StrokeThickness="2"
           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);
this.rect.strokeThickness="5";

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 online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and 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 Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.