SpriteHand
Module Border
  Finding a XAML Element by Name at Runtime
Module Border
Location: BlogsAndy's Blog    
Posted by: host 7/14/2008 4:52 PM

In ASP.NET, it's possible to get a reference to a control by Id at runtime using the FindControl method - something like this:

Label lblCustomerName = (Label) item.FindControl("lblCustomerName");

This can be helpful in dynamic code which might need to iterate through a large collection of elements in XAML.

In Silverlight, there is no FindControl method, but we can still get a reference to an object by name using the FindName method of a container:

TextBlock lblCustomerName = cnvContainer.FindName("lblCustomerName") as TextBlock

We can also access the Children collection of a container and query using a lambda expression:

TextBlock lblCustomerName = (cnvContainer.Children.First<UIElement>(label => label.GetValue(Canvas.NameProperty).ToString() == "lblCustomerName")) as TextBlock;

In the above example, we are getting a reference to an object named lblCustomerName inside a canvas named cnvContainer. We do so by using a lambda expression on the Children property, along with the Canvas.NameProperty which gives the variable (x:Name) property of a UIElement.

Permalink |  Trackback

Title:
Comment:
Add Comment   Cancel 
Module Border Module Border
Module Border
  Blog_List
Module Border
Module Border Module Border
Module Border
  Subscribe
Module Border

RSS

Module Border Module Border
Module Border
  Diversions
Module Border

DESTROY ALL INVADERS
A scrolling shooter game where the objective is to destroy the invading UFO's flying over a neighborhood of your choosing. Imagery provided by Microsoft Virtual Earth. Created using Silverlight 2.
PLAY IT

INFO AND CODE



SORT THE FOOBARS
A game where you need to sort the good foobars from the bad ones. Created using Silverlight 2 and the Farseer Physics engine.
PLAY IT

MORE INFO



POLYGON PHYSICS DEMO
A demo showing polygon physics where the user draws physics objects with the mouse. Created using Silverlight 2 and the Farseer Physics engine.
PLAY IT

MORE INFO



SILVERLIGHT ROCKS!
Destroy the asteroids before they destroy your ship! Created using Silverlight 2.
PLAY IT

INFO AND CODE



FISH GAME
A simple game of harpoon-the-fish. Written using the AJAX Sprite Toolkit.
PLAY IT

INFO AND CODE

Module Border Module Border
Module Border
  Search_Blog
Module Border
Module Border Module Border
Module Border
  Blog_Archive
Module Border
Module Border Module Border
Copyright (c) 2008 andy.beaulieu.com - Login