Установка положения полосы прокрутки ListBox
-
03-07-2019 - |
Вопрос
Могу ли я программно установить положение полосы прокрутки WPF ListBox?По умолчанию я хочу, чтобы он располагался в центре.
Решение
Чтобы переместить вертикальную полосу прокрутки в ListBox, выполните следующие действия:
- Назовите свой список (x:Name="myListBox").
- Добавить событие Loaded для окна (Loaded="Window_Loaded")
- Реализуйте событие Loaded, используя метод:Прокрутка по вертикали смещение
Вот рабочий образец:
КСАМЛ:
<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>
С#
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);
}
}
}
Другие советы
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
или
myListBox.SelectedIndex = midPoint
Это зависит от того, хотите ли вы, чтобы средний элемент был просто показан или выбран.
Я только что немного изменил код Zamboni и добавил расчет позиции.
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));
Я не думаю, что у ListBox'ов это есть, но у ListViews есть Обеспечить видимость метод, который перемещает полосу прокрутки в нужное место, чтобы обеспечить отображение элемента.
Не связан с StackOverflow