Ray*_*rns 12
如果您的所有商品都具有相同的高度,则此问题可能有意义.否则,当您向上和向下滚动ComboBox以查看项目列表的不同部分时,您的ComboBox会在滚动时变得越来越大.
如果您的所有物品都是相同的高度,使用附属物品很容易做到这一点:
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);
}));
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个属性,你可以写:
<ComboBox ...
my:ComboBoxHelper.MaxDropDownItems="8" />
Run Code Online (Sandbox Code Playgroud)
没有直接的方法来表示显示 X 个项目。您必须使用该MaxDropDownHeight
属性来限制其大小。由于此属性不是由控件计算的,并且是完全可自定义的,因此您可以编写一些内容来计算项目的高度,然后将其乘以要显示的最大项目数,然后根据MaxDropDownHeight
它进行设置。