Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ComboBox MaxDropDownItems

Tags:

c#

combobox

wpf

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

like image 671
Kevin Avatar asked Jun 10 '10 20:06

Kevin


1 Answers

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" />
like image 168
Ray Burns Avatar answered Sep 28 '22 12:09

Ray Burns