Pages

Sunday, August 16, 2009

AutoResizing ComboBox Silverlight

AutoResizing ComboBox Silverlight

All Silverlight 2.0 enthusiasts have faced an annoying known issue with a databound ComboBox:

the dropdown popup resizes itself only the first time it is shown.

After its first initialization, no matter if you bind a new datasource with fewer or more elements, the dropdown persists its original height.

One workaround is the following:

  1. store the Properties from the original ComboBox
  2. delete the ComboBox removing it from its container
  3. create a new ComboBox and place it in the container
  4. recover the stores Properties
  5. bind the new DataSource to the newly created combobox

Well, many of us will agree this workaround is annoying as the original issue was...

Here is my try to create a new ComboBox inheriting the original one.

It overrides the OnItemsChanged method, trying to guess the height needed to render the Items within the dropdown popup.


using System.Windows.Controls;

namespace CodeGolem.Controls
{
public class ComboBox : System.Windows.Controls.ComboBox
{
private double _maxDropDownHeight = 0;

public new double MaxDropDownHeight
{
get { return _maxDropDownHeight; }
set { _maxDropDownHeight = value; }
}

protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);

ScrollViewer scrollViewer = (ScrollViewer)GetTemplateChild("ScrollViewer");
scrollViewer.ScrollToVerticalOffset(0);
scrollViewer.ScrollToHorizontalOffset(0);


Border popupBorder = (Border)GetTemplateChild("PopupBorder");
double height = (ActualHeight - 1) * Items.Count + 5;
popupBorder.Height = _maxDropDownHeight > 0 && height > _maxDropDownHeight ? _maxDropDownHeight : height;
}
}
}

I tried this only without templated Items.
The final height is calculated supposing that the items' height is equal to the ComboBox height minus one.
I add also five pixels for upper and lower margins.

The height-calculating formula may be improved or changed to reflect your own needs.

Anyway I think having a custom ComboBox control within our projects is less annoying than re-creating each combo everytime we update their datasource.

Hope this helps all you readers... while we all confidently wait for the final Silverlight 3.0 release!

No comments:

Post a Comment