Is there anyway to set the maximum number of drop down items rather than the max drop down height in WPF? Thanks! -Kevin
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With