Setting the scrollbar position of a ListBox
20,910
Solution 1
To move the vertical scroll bar in a ListBox do the following:
- Name your list box (x:Name="myListBox")
- Add Loaded event for the Window (Loaded="Window_Loaded")
- Implement Loaded event using method: ScrollToVerticalOffset
Here is a working sample:
XAML:
<Window x:Class="ListBoxScrollPosition.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Window_Loaded"
Title="Main Window" Height="100" Width="200">
<DockPanel>
<Grid>
<ListBox x:Name="myListBox">
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
<ListBoxItem>Zamboni</ListBoxItem>
</ListBox>
</Grid>
</DockPanel>
</Window>
C#
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Get the border of the listview (first child of a listview)
Decorator border = VisualTreeHelper.GetChild(myListBox, 0) as Decorator;
if (border != null)
{
// Get scrollviewer
ScrollViewer scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null)
{
// center the Scroll Viewer...
double center = scrollViewer.ScrollableHeight / 2.0;
scrollViewer.ScrollToVerticalOffset(center);
}
}
}
Solution 2
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
or
myListBox.SelectedIndex = midPoint
It depends on if you want the middle item just shown, or selected.
Related videos on Youtube
Author by
ScottG
I am a software architect in Detroit, Michigan specializing in e-commerce on the Microsoft stack (ASP.NET MVC, WPF, WCF, SQL Server, and C#). I write software that integrates with Amazon MWS and AWS, Paypal, Google, Jet, and ChannelAdvisor among others.
Updated on December 05, 2020Comments
-
ScottG over 3 years
Can I programatically set the position of a WPF ListBox's scrollbar? By default, I want it to go in the center.
-
ScottG over 15 yearsthis just scrolls it into view. I need it to scroll right to the center. But thanks
-
Sam over 15 yearsEnsureVisible is a windows.Forms function, the question was about WPF. In WPF there is no EnsureVisible method as far as I can tell.