Over a million developers have joined DZone.

“Flattening-out” ListBox Control

DZone's Guide to

“Flattening-out” ListBox Control

· ·
Free Resource

The ListBox control is by default scrollable. Naturally, you would want that feature when you have more items than can fit the screen. However, if ListBox is part of another ListBox or inside ScrollViewer, you might get “double scroll” effect.

Double scrolling with nested ListBoxes

Another use case is showing a limited amount of items which you don’t want to or you cannot predict in advance. If it is a part of a ScrollViewer or if it is embedded inside another ListBox, you don’t want double scroll to appear, you want to have one master scroll.

To achieve that, you must modify the default control template and instead of wrapping ItemsPresenter in a ScrollViewer, wrap it inside a Borderelement. Here is the full XAML for that:

<ControlTemplate TargetType="ListBox" x:Key="FlatListBoxControlTemplate">
	<Border x:Name="Border"
			BorderBrush="{TemplateBinding BorderBrush}"
			BorderThickness="{TemplateBinding BorderThickness}"
			Background="{TemplateBinding Background}"
			Padding="{TemplateBinding Padding}">
		<ItemsPresenter />

Astute readers might notice that one property is not bound: ForegroundBorder doesn’t support it and you cannot use it in the inheritance chain. This is a very nice technique when you don’t want your ListBox to scroll.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}