.NET Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 69 posts at DZone. You can read more from them at their website. View Full User Profile

“Flattening-out” ListBox Control

09.25.2013
| 1436 views |
  • submit to reddit

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 />
	</Border>
</ControlTemplate>

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 Toni Petrina, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)