Friday, April 18, 2008

Silverlight 2: Communicating Between Controls

In an attempt to keep pace with the one a week challenge, here is another post! Does two in one week make up for none in the last?

I have been working on my first production Silverlight application, using Silverlight 2 Beta 1. I have been playing around with how best to structure the site, with maintainability in mind. As a result, I have several user controls that encapsulate specific pieces of functionality. I am treating the Page.xaml that is loaded when my site loads conceptually as my "Master Page", containing different user controls, etc. All in all, I am pretty satisfied.

I came across the need for a user control to communicate with another user control. I started down the route of raising an event and registering handlers. Problem is that my first user control is contained in another user control, and I didn't want to add events and handlers to both user controls to propagate all the way up to my parent page.

I wrote a quick extension method that uses Generics that solves my problem. You can use it to retrieve a specific ancestor of an element... quite useful.



Here is how I called it within my user control...



In unit testing, I saw a variety of StackPanels, Grids, and UserControls on the way to my desired Page. Its important to note that if you have a reference to a Control, its .Parent property will usually give you a container such as a Grid, Canvas, or StackPanel. If you need an "Grandparent" or "Great Grandparent", this extension works well.

No comments:

Post a Comment