有没有办法在WPF中设置下拉列表项的最大数量而不是最大下拉高度呢?
谢谢!
-Kevin
如果你的所有项都具有相同的高度,那么这个问题才有意义。否则,当你滚动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);
}));
}
}
使用此属性,您可以编写以下内容:
<ComboBox ...
my:ComboBoxHelper.MaxDropDownItems="8" />
没有直接的方法来显示X个项目。您必须使用MaxDropDownHeight
属性来限制其大小。由于此属性不是由控件计算的,并且完全可自定义,因此您可以编写一些代码来计算项目的高度,然后将其乘以要显示的最大项目数,然后根据此设置MaxDropDownHeight
。
我曾经遇到过类似的问题,即组合框下拉列表无法占据整个垂直空间 - 即使有足够的垂直空间可以容纳20个项目,但在3到4个项目后仍会出现垂直滚动条。我创建了一个tempList,并将comboboxitems添加到该列表中。将此tempList分配给ComboBox的ItemsControl绑定,这样就可以给组合框设置初始下拉高度。 现在,组合框可以显示20个项目而不需要垂直滚动条。
MaxDropDownHeight无效,无论在视图初始化之前还是之后都是如此。
希望对某些人有所帮助!
谢谢,
RDV