Skip to content

WPF Smooth ListBox Control Template

In a previous article we developed a ScrollViewer which supports smooth scrolling. That means scrolling is animated and smooth.

In this article I want to show you how to apply that ScrollViewer to a ListBox. There are only a few steps to do:

  1. Create the default ListBox Control Template using Visual Studio. Please, follow the steps described here.
  2. Change the property setter ‘ScrollViewer.CanContentScroll’ from true to false because smooth scrolling is only supported for physical scrolling.
  3. Change the ScrollViewer class to SmoothScrollViewer.
  4. Apply the style to your ListBox

Smooth ListBox Control Template Listing:

<SolidColorBrush x:Key="ListBox.Static.Background" Color="#FFFFFFFF"/> <SolidColorBrush x:Key="ListBox.Static.Border" Color="#FFABADB3"/> <SolidColorBrush x:Key="ListBox.Disabled.Background" Color="#FFFFFFFF"/> <SolidColorBrush x:Key="ListBox.Disabled.Border" Color="#FFD9D9D9"/> <Style x:Key="SmoothListBox" TargetType="{x:Type ListBox}"> <Setter Property="Background" Value="{StaticResource ListBox.Static.Background}"/> <Setter Property="BorderBrush" Value="{StaticResource ListBox.Static.Border}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> <Setter Property="ScrollViewer.PanningMode" Value="Both"/> <Setter Property="Stylus.IsFlicksEnabled" Value="False"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBox}"> <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true"> <scrollViewer:SmoothScrollViewer Focusable="false" Padding="{TemplateBinding Padding}"> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </scrollViewer:SmoothScrollViewer> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Background" TargetName="Bd" Value="{StaticResource ListBox.Disabled.Background}"/> <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource ListBox.Disabled.Border}"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsGrouping" Value="true"/> <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false"/> </MultiTrigger.Conditions> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
Code language: HTML, XML (xml)
Copyright (c) by Thomas Kemp, 2021