В Windows Forms у элемента управления ComboBox есть свойство MaxDropDownItems, которое позволяет задавать количество элементов отображаемых в выпадающем списке. К сожалению, разработчики WPF не реализовали это свойство. Но, к счастью, они создали новый инструмент, который позволяет это сделать: присоединяемые свойства зависимости. То, что мы сейчас будем делать, возможно только для выпадающих списков, высота элементов которых одинакова.
Создадим новый проект. Я назвал его ComboBoxControl.MaxDropDownItems. Теперь добавим в него класс ComboBoxHelper. Наследуем наш класс от ComboBox
class ComboBoxHelper : ComboBox
{
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);
}
});
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);
}));
}
}
Использование:
<Window x:Class="ComboBoxControl.MaxDropDownItems.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:ComboBoxControl.MaxDropDownItems"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox my:ComboBoxHelper.MaxDropDownItems="10" VerticalAlignment="Top">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>3</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>5</ComboBoxItem>
<ComboBoxItem>6</ComboBoxItem>
<ComboBoxItem>7</ComboBoxItem>
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>9</ComboBoxItem>
<ComboBoxItem>10</ComboBoxItem>
<ComboBoxItem>11</ComboBoxItem>
<ComboBoxItem>12</ComboBoxItem>
<ComboBoxItem>13</ComboBoxItem>
<ComboBoxItem>14</ComboBoxItem>
<ComboBoxItem>15</ComboBoxItem>
<ComboBoxItem>16</ComboBoxItem>
<ComboBoxItem>17</ComboBoxItem>
<ComboBoxItem>18</ComboBoxItem>
<ComboBoxItem>19</ComboBoxItem>
<ComboBoxItem>20</ComboBoxItem>
</ComboBox>
</Grid>
</Window>
Исходный код: [download id=”18″]
