October 15, 2011

Disabled list items with enabled scrollbars

In several scenarios we disables list box preventing user to do any action against list items. When you disable list box it also disables scrollbars preventing scrolling of list items. However in some cases we might want to show scrollable disabled items to view list contents. To solve this issue there are various options available including implementation of custom list box with properties to enable scrolls. Following code snippet shows a technique to disable only list items allowing user to scroll items. Note the ScrollViewer and ItemsPresenter properties in list box control template which governs enabling scrollbars while disabling list items.


<Window x:Class="WpfTest.Window2"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Window8" Height="300" Width="300">
<ListBox  Margin="10,10,10,10" Height="130" Width="100">
<Style TargetType="ListBox"  >
<Setter Property="Template">
<ControlTemplate TargetType="ListBox">
<Border BorderBrush="Black" BorderThickness="1">
<ScrollViewer IsEnabled="True" >
<ItemsPresenter IsEnabled="False"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
<ListBoxItem>Item 4</ListBoxItem>
<ListBoxItem>Item 5</ListBoxItem>
<ListBoxItem>Item 6</ListBoxItem>    
<ListBoxItem>Item 7 - Long length item</ListBoxItem>
<ListBoxItem>Item 8</ListBoxItem>
<ListBoxItem>Item 9</ListBoxItem>