gpt4 book ai didi

c# - WPF 组合框 MaxDropDownItems

转载 作者:太空狗 更新时间:2023-10-29 18:19:24 27 4
gpt4 key购买 nike

在 WPF 中是否可以设置最大下拉项数而不是最大下拉高度?谢谢!-凯文

最佳答案

只有当您的所有元素都具有相同的高度时,这个问题才有意义。否则,当您上下滚动 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" />

关于c# - WPF 组合框 MaxDropDownItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018267/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com