Silverlight UI Rant #2 – ListBoxItem


Posted on 12th February 2009 by r2 in Silverlight |UI Rant

Tonight’s recipient of my UI Rant is the Silverlight 2 ListBox, or more specifically, the ListBoxItem.  A client recently asked me to provide an alternating row style like the DataGrid for the ListBox.  Now, if you’ve ever tried to add a border or background to your ListBoxItem, you’ve seen this:


No problem, you say, I will simply set the HorizontalContentAlignment of my ListBox to Stretch and all should be good.  When that doesn’t do it, you’ll probably try creating/editing the ListBox’s ItemTemplate….maybe adding a Grid and setting its HorizontalAlignment to Stretch.  This too will fail.

Turns out, the problem is not with your ItemTemplate or even with the ListBox itself.  The issue is in the container that actually contains your Item and that is the ListBoxItem.  The property on the ListBox that allows you to set a custom style for this ListBoxItem is called ItemContainerStyle.  Armed with this information, you quickly throw together a style for your ListBoxItem, maybe like so:

  1. <Style TargetType="ListBoxItem" x:Key="ItemContainerStyle">
  2.     <Setter Property="Padding" Value="3" />
  3.     <Setter Property="HorizontalContentAlignment" Value="Stretch" />
  4.     <Setter Property="VerticalContentAlignment" Value="Top" />
  5.     <Setter Property="Background" Value="Transparent" />
  6.     <Setter Property="BorderThickness" Value="1" />
  7. </Style>

And then add that to your ListBox, like so:

  1. <ListBox Margin="8,8,10,8" x:Name="defaultListBox" ItemsSource="{Binding}"
  2.     ItemTemplate="{StaticResource EmployeeItemTemplate}"  
  3.          ItemContainerStyle="{StaticResource ItemContainerStyle}"/>

Hit F5 and just about the time you congratulate yourself on solving this, the Silverlight Loading Animation will finish and you’ll discover that your ListBox still looks exactly like the original screenshot above.  So, what happened?

What happened is that the default ControlTemplate for the ListBoxItem has its HorizontalAlignment hard-coded to Left and no matter what you do when setting the properties, it will always be Left.  If you’ll do a little diving into the full default style for ListBoxItem, courtesy of SilverlightDefaultStyleBrowser (highly recommended), you’ll see exactly what I’m talking about in the ContentPresenter’s HorizontalAlignment property:


The good news is that because you have the ability to replace the Template of any control in Silverlight, you can simply "correct" this hard-coded problem by replacing the hard-coded Left value for HorizontalAlignment with {TemplateBinding HorizontalContentAlignment}, so your final new Style would look like this:

  1. <Style TargetType="ListBoxItem" x:Key="StretchedItemContainerStyle">
  2.     <Setter Property="Padding" Value="3" />
  3.     <Setter Property="HorizontalContentAlignment" Value="Stretch" />
  4.     <Setter Property="VerticalContentAlignment" Value="Top" />
  5.     <Setter Property="Background" Value="Transparent" />
  6.     <Setter Property="BorderThickness" Value="1" />
  7.     <Setter Property="TabNavigation" Value="Local" />
  8.     <Setter Property="Template">
  9.         <Setter.Value>
  10.             <ControlTemplate TargetType="ListBoxItem">
  11.                 <Grid Background="{TemplateBinding Background}">
  12.                     <VisualStateManager.VisualStateGroups>
  13.                         <!– removed VSM code for brevity  –>
  14.                     </VisualStateManager.VisualStateGroups>
  15.                     <Rectangle x:Name="fillColor" Opacity="0" Fill="#FFBADDE9"   
  16.                        IsHitTestVisible="False" RadiusX="1" RadiusY="1" />
  17.                     <Rectangle x:Name="fillColor2" Opacity="0" Fill="#FFBADDE9"
  18.                        IsHitTestVisible="False" RadiusX="1" RadiusY="1" />
  19.                     <ContentPresenter x:Name="contentPresenter" Content="{TemplateBinding Content}"
  20.                        ContentTemplate="{TemplateBinding ContentTemplate}"
  21.                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
  22.                        Margin="{TemplateBinding Padding}" />
  23.                     <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1"
  24.                          StrokeThickness="1" Visibility="Collapsed" RadiusX="1" RadiusY="1" />
  25.                 </Grid>
  26.             </ControlTemplate>
  27.         </Setter.Value>
  28.     </Setter>
  29. </Style>

Now your ListBoxItem will respect the value you are setting for its HorizontalContentAlignment in your Setter above and your ListBox will finally look like this:


Hope that saves someone a little frustration.  I’ll continue on to adding the alternating row style in another post.

Here is the live sample.

Here is the source code.

Silverlight UI Rant #1 – DataGrid Last Column Fill


Posted on 6th February 2009 by r2 in Silverlight |Silverlight 2 |UI and Usability |UI Rant

If you’ve used the the Silverlight 2 DataGrid, you’ve no doubt seen this:


I really hate when this happens!  I’ve seen several forum discussions where folks were looking to get rid of this nastiness, so I know I’m not the only one losing sleep over it.  I haven’t come across a solution in anything I’ve seen and so now that I have one, I thought I’d share it.

I ran into this a few weeks back and tried most of the obvious things with defining the DataGridColumns myself rather than auto-generating them.  In these defined DataGridColumns, I tried setting the Width of the last column to "*" just like you would a standard Grid.ColumnDefinition if you wanted to have it take up the remainder of the space.  This did nothing more than invite my buddy, AG_E_PARSER_BAD_PROPERTY, to show up…again.  It appears that star-sizing isn’t yet implemented for DataGridColumn derivatives.

This morning I was finally able to grab a few minutes to dive into DataGrid and find out what I could do about this.  I decided to create an ExtendedDataGrid and add a LastColumnFill DependencyProperty similar to way the DockPanel has a LastChildFill. Most of the work is happening in this method which is called if the LastColumnFill is true:

  1. private void AdjustLastColumnWidth(Size finalSize)
  2. {
  3.     // get the Vertical ScrollBar
  4.     ScrollBar scrollBar = this.GetTemplateChild("VerticalScrollbar") as ScrollBar;
  6.     // compute the width to allow for the scrollbar based on it's visibility.
  7.     double scrollBarWidthAllowance =
  8.         (scrollBar != null && scrollBar.Visibility == Visibility.Visible) ?
  9.         scrollBar.ActualWidth + 2 : 2;
  11.     // compute the width of all the columns excluding the last one
  12.     var widthOfAllButLastColumn =
  13.         Columns.TakeWhile(c => c != Columns.Last() && c.Visibility == Visibility.Visible)
  14.         .Sum(c => c.ActualWidth);
  16.     // set the last column width    
  17.     Columns.Last().Width = new DataGridLength(finalSize.Width
  18.         - widthOfAllButLastColumn – scrollBarWidthAllowance);
  20. }

This is the result:


Much better!  The live demo shows it with and without a vertical scrollbar.  Note that it also handles
auto-generated DataGridColumns if that’s your thang.

Here’s the live demo.

Here’s the code.