Blog Bloginski

Dude, welcome to my pet shop!!

Tracking ItemsControl Container Elements

without comments

Silverlight ItemsControls do not provide an easy way to retrieve the generated item containers for the items within the ItemsControl.  In WPF the ItemContainerGenerator provides the item generation for the ItemsControl as well as nice helper methods to interact with those containers.  I needed this functionality for some silverlight controls that I was working on so I wrote a small class to make this easier.  If item container generation is a totally new concept to you check out Dr. WPF’s great overview here.  The ItemContainerHelper class provides four helper methods: ContainerFromIndex, ContainerFromItem, IndexFromContainer, and ItemFromContainer.  The functionality provided by these methods is pretty straight forward. 

In order to use these methods within a custom ItemsControl you just need to do two things which are illustrated in the ContainerTrackingListBox class in the sample linked below.  In PrepareContainerForItemOverride you need to call the AddContainer method on an instance of ItemContainerHelper within your ItemsControl.  PrepareContainerForItemOverride is called by Silverlight when the container has been created.  You also need to tell ItemContainerHelper about any changes to the items in the ItemsControl.  To do this call IncorporateItemChange from within the OnItemsChanged override of the ItemsControl.

That’s all there is to it and now you can easily access the item containers generated by an ItemsControl.

You can download the sample code using this class here.

Written by josh

September 23rd, 2008 at 11:48 pm

Posted in Silverlight

Leave a Reply