tags:

views:

51

answers:

2

Is there anyway to set the maximum number of drop down items rather than the max drop down height in WPF? Thanks! -Kevin

+1  A: 

There is no direct way to say display X number of items. You must use the MaxDropDownHeight property to limit it's size. Since this property is no calculated by the control and is full customizable you could write something to calculate an item's height and then multiple that by the max items you want to display and then set MaxDropDownHeight based on it.

Kelsey
+1 Right idea, as long as all the items are the same height. This should probably be done in an attached property. I'll add an answer that has the actual code to do this.
Ray Burns
A: 

This question may only be meaningful if all of your items have the same height. Otherwise as you scroll your ComboBox up and down to see different portions of the item list your ComboBox would get bigger and smaller as you scroll.

If all of your items are the same height, it's very easy to do this using an attached property:

public class ComboBoxHelper : DependencyObject
{
  public static int GetMaxDropDownItems(DependencyObject obj) { return (int)obj.GetValue(MaxDropDownItemsProperty); }
  public static void SetMaxDropDownItems(DependencyObject obj, int value) { obj.SetValue(MaxDropDownItemsProperty, value); }
  public static readonly DependencyProperty MaxDropDownItemsProperty = DependencyProperty.RegisterAttached("MaxDropDownItems", typeof(int), typeof(ComboBoxHelper), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) =>
    {
      var box = (ComboBox)obj;
      box.DropDownOpened += UpdateHeight;
      if(box.IsDropDownOpen) UpdateHeight(box, null);
    }
  });

  private static void UpdateHeight(object sender, EventArgs e)
  {
    var box = (ComboBox)sender;
    box.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
      {
        var container = box.ItemContainerGenerator.ContainerFromIndex(0) as UIElement;
        if(container!=null && container.RenderSize.Height>0)
          box.MaxDropDownHeight = container.RenderSize.Height * GetMaxDropDownItems(box);
      }));
  }
}

With this property you can write:

<ComboBox ...
   my:ComboBoxHelper.MaxDropDownItems="8" />
Ray Burns