ComboBox Displaying a Drop-Down Menu

,

While building a code mock-up of a user interface this week, I encountered an unusual requirement. The design called for ComboBox-looking control that displayed a menu (instead of an items list) when expanded.

A combo box displaying a menu…

Simply placing MenuItems in the combo box’s items collection didn’t work. The drop-down would display the menu items but nested (child) menus would not expand. (Apparently, menu items need to be within a menu in order to function properly.) Wrapping the menu items in a Menu fixed the nested menus issue. However, expanding the drop-down caused a menu bar—instead of a menu—to appear. Unacceptable.

…or a menu styled like a combobox?

Instead of attempting to get a combo box to show a menu, what if I tried styling a menu to look like a comob box?

Much easier!

<Menu HorizontalAlignment="Left">
    <-- This first menu item is styled to look like a combo box. -->
    <MenuItem>
	<MenuItem.Header>
	    <StackPanel Orientation="Horizontal">
		<-- Yes, the access key works! -->
		<Label Padding="0" Margin="0 0 0 1">_Sort by</Label>
		<Border>
			<-- The toggle button looks identical to the one used on a combo box
				because I based the definition below on the relevant portion of the
				combo box's default control template. -->
		    <ToggleButton IsChecked="False" IsHitTestVisible="False"
				    BorderBrush="{TemplateBinding Border.BorderBrush}"
				    Background="{TemplateBinding Panel.Background}">
			<ToggleButton.Style>
			    <Style TargetType="ToggleButton">
				<Setter Property="OverridesDefaultStyle" Value="True" />
				<-- The toggle control just needs visually appear. It doesn't
					need to receive focus or be a tab stop. -->
				<Setter Property="Focusable" Value="False" />
				<Setter Property="IsTabStop" Value="False" />
				<Setter Property="Control.Template">
				    <Setter.Value>
					<ControlTemplate TargetType="ToggleButton">
					    <Path Data="M0,0L3.5,4 7,0z" Fill="#FF000000" Name="Arrow"
									Margin="3,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
					</ControlTemplate>
				    </Setter.Value>
				</Setter>
			    </Style>
			</ToggleButton.Style>
		    </ToggleButton>
		</Border>
	    </StackPanel>
	</MenuItem.Header>
	<MenuItem Header="_Name">
	    <MenuItem Header="_Last" />
	    <MenuItem Header="_First" />
	</MenuItem>
    </MenuItem>
</Menu>

The design I was mocking called for the combo box to have square edges and a white background (reflected in the styling of the above example). Implementing rounded edges and a chrome background—to match the typical appearance of a combo box—is just a matter of changing the styling.

2 thoughts on “ComboBox Displaying a Drop-Down Menu

  1. Marko

    Thanks!! This is just what I needed. I am having trouble rounding those corners, though. Any help on that would be appreciated.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *