Scrolling In ItemsControl
May 9, 2008 by lee
Here is one way to control a ScrollViewer without Scrollbar
Let say we have this basic UI
A button on the left to scroll to the left, A button on the right to scroll right and ItemsControl between the buttons which is what we are going to scroll when the buttons are clicked
<UserControl.Resources>
<DataTemplate x:Key=”dt”>
<TextBlock Margin=”5,0,0,0″ Text=”{Binding FirstName}”></TextBlock>
</DataTemplate>
</UserControl.Resources>
<Canvas>
<Grid Width=”400″ Height=”50″>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=”50″></ColumnDefinition>
<ColumnDefinition Width=”300″></ColumnDefinition>
<ColumnDefinition Width=”50″></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Content=”left” x:Name=”btnLeft” Grid.Column=”0″></Button>
<ScrollViewer Grid.Column=”1″ VerticalScrollBarVisibility=”Hidden” HorizontalScrollBarVisibility=”Hidden” x:Name=”sv” Width=”300″ Height=”50″>
<ListBox x:Name=”list1″ ItemTemplate=”{StaticResource dt}”>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation=”Horizontal”></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</ScrollViewer>
<Button Content=”right” x:Name=”btnRight” Grid.Column=”2″></Button>
</Grid>
</Canvas>
we hide the scrollbars of the scrollviewer and we have 2 buttons to scroll left and right. Lets bind the listbox to an ItemsSource and attach eventhandlers to handle the buttonclick events
List<Customer> customers = new List<Customer>();
for (int i = 0; i < 20; i++)
customers.Add(new Customer { FirstName = “Customer..” + i.ToString() });
list1.ItemsSource = customers;
btnLeft.Click += new RoutedEventHandler(btnLeft_Click);
btnRight.Click += new RoutedEventHandler(btnRight_Click);
In the button click events we can change the ScrollToHorizontalOffset and HorizontalOffset to get the desired effect
void btnRight_Click(object sender, RoutedEventArgs e)
{
if (sv.ScrollableWidth > 0)
sv.ScrollToHorizontalOffset(sv.HorizontalOffset + 10);
}
{
if (sv.HorizontalOffset > 0)
sv.ScrollToHorizontalOffset(sv.HorizontalOffset - 10);
}
[...] Datagrid Date Column Michael Sync adds some styling to the DataGrid, and has the code on his site. Scrolling In ItemsControl Lee Shows a way to scroll an ScrollViewer by using buttons instead of a scrollbar… I like [...]