Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...