Frage

Kann ich programmatisch die Position eines WPF ListBox Scrollbar gesetzt? Standardmäßig möchte ich es in der Mitte gehen.

War es hilfreich?

Lösung

Um die vertikale Bildlaufleiste in einem ListBox zu bewegen wie folgt vor:

  1. Name Ihr Listenfeld (x: Name = "myListBox")
  2. Fügen Sie Loaded-Ereignis für das Window (Loaded = "Window_Loaded")
  3. Implementieren Loaded-Ereignis mit der Methode: ScrollToVerticalOffset

Hier ist ein funktionierendes Beispiel:

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

Andere Tipps

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

oder

myListBox.SelectedIndex = midPoint

Es hängt davon ab, ob Sie das mittlere Element wollen nur gezeigt, oder ausgewählt werden.

Ich habe geändert nur ein bisschen Code von Zamboni und hinzugefügt Positionsberechnung.

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

Ich glaube nicht, Listboxen haben, dass aber Listviews haben die EnsureVisible Methode, die die Scrollbar an dem Ort benötigt, um bewegt, um sicherzustellen, ein Element angezeigt wird.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top