问题
Can I programatically set the position of a WPF ListBox's scrollbar? By default, I want it to go in the center.
回答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);
}
}
}
回答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.
回答3:
I've just changed a bit code of Zamboni and added position calculation.
var border = VisualTreeHelper.GetChild(list, 0) as Decorator;
if (border == null) return;
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer == null) return;
scrollViewer.ScrollToVerticalOffset((scrollViewer.ScrollableHeight/list.Items.Count)*
(list.Items.IndexOf(list.SelectedItem) + 1));
回答4:
I have a ListView named MusicList. MusicList automatically moves to the next element after playing a music. I create an event handler for Player.Ended event as follows (a la Zamboni):
if (MusicList.HasItems)
{
Decorator border = VisualTreeHelper.GetChild(MusicList, 0) as Decorator;
if (border != null)
{
ScrollViewer scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null)
{
MusicList.ScrollIntoView(MusicList.SelectedItem);
}
}
}
You get the next element seen at the bottom.
回答5:
I don't think ListBoxes have that, but ListViews have the EnsureVisible method that moves the scrollbar to the place needed in order to make sure an item is shown.
来源:https://stackoverflow.com/questions/159506/setting-the-scrollbar-position-of-a-listbox