Friday, June 5, 2009

How to add scrollbars to ItemsControl on WPF?

 
There are two ways to do this. The simpler and most easier way is to warp the ItemsControl with a ScrollViewer, but there are some other problems on this solution. Each case we might want to use ScrollViewer. In those case we can modify the  control template and add proper code in ControlTemplate so that we do not have any problem layout.
 
Bellow few simple line of codes is given to demonstrate the idea.
<ItemsControl ItemsSource="{Binding EventWithoutDateColumns}" Margin="10">
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>

There are some other way to do that, and that is, to use styles and also apply the style globally so that it effect the whole application. In this way the whole application will have ScrollViewer with particular style in every ItemsControl.

 

Bellow few simple line of code is given Bellow.

 

<Style TargetType="{x:Type ItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Hope this helps to somebody, Cheers.