2008-10-01 157 views

回答

7

要移動在ListBox垂直滾動條執行以下操作:

  1. 名稱列表框(X:NAME = 「myListBox」)
  2. 的窗口中添加Loaded事件(加載=「Window_Loaded 「)
  3. 實現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); 
    } 
    } 
} 
+1

這對我很好。 – 2010-09-23 17:24:32

-1

我不認爲ListBox有那個,但ListViews有EnsureVisible方法將滾動條移動到所需的位置,以確保顯示一個項目。

+0

EnsureVisible是一個windows.Forms函數,問題是關於WPF。據我所知,在WPF中沒有EnsureVisible方法。 – Sam 2008-10-17 12:19:01

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

myListBox.SelectedIndex = midPoint 

,如果你想中間的項目剛剛展示,或選擇要看。

+0

這只是將其滾動到視圖中。我需要它滾動到中心。但是,謝謝 – ScottG 2008-10-03 14:17:01

0

我只是改變了贊博尼的位代碼並添加位置計算。

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