OpenLightGroup Blog


Blogs from

Dynamic ListBox Item Templates

This is a very short and sweet post about dynamically switching the ItemTemplate property of a Silverlight ListBox at runtime. First we will start with a little background of what led to this article.

I am currently working on an application that contains a list of pediatric patients and their parents. I was recently given a requirement to display a parent name to one group of medical professional and the patient name to another group. However, either group should be able to toggle this display to allow searching on either the parent or patient.

Knowing that in Silverlight, simple is usually the correct answer, I figured this should in fact be simple. Thankfully, I was correct and after only a few minutes I had the following solution working.

  If Me.SearchByParent.IsChecked Then
            Me.PatientListBox.SetValue(ListBox.ItemTemplateProperty, _
            Me.PatientListBox.SetValue(ListBox.ItemTemplateProperty, _
 End If


I have created two different DataTemplates to display the appropriate information for either the parent or the patient. These are added to the UserControl.Resources and then used when dynamically setting the ItemTemplateProperty DependencyProperty of the ListBox instance. The reason the DependencyProperty is used is to avoid an InvalidCastException that is thrown if setting the ItemTemplate instance property directly.

I did not come up with much on this in the brief searching I did online, so I thought I would get it out there for others.


Comments are closed.
Showing 2 Comments
Avatar  Ian T. Lackey 8 years ago

I was in the same boat, this one came out of a lot of trial and error. Figured I had to post it to try and prevent others from running the same circles. :)<br><br>Thanks for the feedback!

Avatar  Matt 8 years ago

Thank you for posting this! I tried many things that did not work before stumbling upon your post