我可以以编程方式设置 WPF ListBox 滚动条的位置吗?默认情况下,我希望它位于中心。
Scott
问问题
20934 次
5 回答
7
要在 ListBox 中移动垂直滚动条,请执行以下操作:
- 命名您的列表框 (x:Name="myListBox")
- 为窗口添加 Loaded 事件 (Loaded="Window_Loaded")
- 使用方法实现 Loaded 事件:ScrollToVerticalOffset
这是一个工作示例:
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);
}
}
}
于 2010-06-12T16:08:00.273 回答
3
Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt\2
myListBox.ScrollIntoView(myListBox.Items(midPoint))
或者
myListBox.SelectedIndex = midPoint
这取决于您是否想要刚刚显示或选择的中间项目。
于 2008-10-01T20:31:52.287 回答
0
我刚刚更改了 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));
于 2012-06-25T20:12:29.127 回答
0
我有一个名为 MusicList 的 ListView。MusicList 在播放音乐后自动移动到下一个元素。我为 Player.Ended 事件创建了一个事件处理程序,如下所示(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);
}
}
}
您会在底部看到下一个元素。
于 2019-12-05T03:06:00.040 回答
-1
我不认为 ListBoxes 有,但 ListViews 有EnsureVisible方法,可以将滚动条移动到所需的位置,以确保显示项目。
于 2008-10-01T20:23:30.247 回答