Coloring a ListBoxItem In Silverlight

by mgordon 6. July 2009 10:47

I was recently trying to display ListBoxItems with different colors based on criteria in the items the list was bound to.  More specifically, the challenge was not in changing the background colors, but with getting the color to fill the entire item.  After much searching, I found a blog post, here, by Ric Robinson that reminded me that I already knew how to fix the problem.

 

Why Setting HorizontalContentAlignment Doesn’t Work

As Ric explains, in the default ControlTemplate the alignment for the item is hard coded to “Left” which means that no matter what you do with the properties of the ListBox or ListBoxItem, the contents of the item will never stretch to fill the container.

 

The Solution

Since Silverlight allows you to override the style of any control, the solution is to create a style that is an exact copy of the default style and modify the HorizontalAlignment property to bind to the HorizontalContentAlignment value specified on the ListBox.  While I was at it, I modified several of the style attributes to suit my liking.

Tags:

Silverlight

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Extensive SEO