设置列表框的滚动条位置 [英] Setting the scrollbar position of a ListBox

查看:108
本文介绍了设置列表框的滚动条位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can I programatically set the position of a WPF ListBox's scrollbar? By default, I want it to go in the center.

推荐答案

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

To move the vertical scroll bar in a ListBox do the following:

  1. 命名您的列表框(x:Name ="myListBox")
  2. 为窗口添加已加载事件(Loaded ="Window_Loaded")
  3. 使用方法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);
    }
  }
}

这篇关于设置列表框的滚动条位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆