设置列表框的滚动条位置

时间:2020-03-06 14:59:45  来源:igfitidea点击:

我可以以编程方式设置WPF ListBox滚动条的位置吗?默认情况下,我希望它位于中间。

解决方案

我不认为ListBoxes具有该功能,但是ListViews具有确保将项目滚动条移动到所需位置的sureVisible方法。

Dim cnt as Integer = myListBox.Items.Count
Dim midPoint as Integer = cnt
myListBox.ScrollIntoView(myListBox.Items(midPoint))

或者

myListBox.SelectedIndex = midPoint

这取决于是否要显示或者选择中间项目。

要在列表框中移动垂直滚动条,请执行以下操作:

  • 命名列表框(x:Name =" myListBox")
  • 为窗口添加已加载事件(Loaded =" Window_Loaded")
  • 使用方法ScrollToVerticalOffset实现Loaded事件

这是一个工作示例:

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);
    }
  }
}