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

有帮助吗?

解决方案

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

  1. 为列表框命名(x:Name =" myListBox")
  2. 为Window添加Loaded事件(Loaded =" Window_Loaded")
  3. 使用方法实现Loaded事件:ScrollToVerticalOffset
  4. 以下是一份工作样本:

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

其他提示

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有 EnsureVisible 方法,将滚动条移动到所需位置,以确保显示项目。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top