2008-10-01 41 views

Odpowiedz

7

Aby przesunąć pionowego paska przewijania w ListBox wykonaj następujące czynności:

  1. Nazwa Twój pole listy (x: Name = "myListBox")
  2. Dodaj Loaded imprezę dla okna (Loaded = "Window_Loaded „)
  3. zrealizować za pomocą metody Loaded zdarzenie: ScrollToVerticalOffset

Oto próbka robocza:

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

To działało świetnie dla mnie. –

+0

Będzie działać tylko wtedy, gdy ListBox użyje domyślnego szablonu –

-1

Nie sądzę, że ListBoxe to ma, ale ListViews ma metodę EnsureVisible, która przenosi pasek przewijania do miejsca potrzebnego, aby upewnić się, że element jest pokazany.

+0

EnsureVisible jest funkcją Windows.Forms, pytanie było o WPF. W WPF nie ma metody "AllowVisible", o ile mogę powiedzieć. – Sam

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

lub

myListBox.SelectedIndex = midPoint 

To zależy od tego, czy chcesz po prostu element środkowy pokazano, lub wybrane.

+0

to po prostu przewija to do widoku. Potrzebuję go, aby przewinąć w prawo do centrum. Ale dziękuję – ScottG

0

Właśnie zmienił kod bitowej Zamboni i dodał obliczenia pozycji.

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)); 
Powiązane problemy