WPF 组合框 MaxDropDownItems [英] WPF ComboBox MaxDropDownItems

查看:25
本文介绍了WPF 组合框 MaxDropDownItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

这个问题可能只有在你所有的项目都具有相同的高度时才有意义.否则,当您上下滚动 ComboBox 以查看项目列表的不同部分时,您的 ComboBox 会随着滚动而变得越来越小.

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

这篇关于WPF 组合框 MaxDropDownItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆