Domanda

Posso impostare a livello di programmazione la posizione di una barra di scorrimento ListBox WPF? Per impostazione predefinita, voglio che vada al centro.

È stato utile?

Soluzione

Per spostare la barra di scorrimento verticale in un ListBox, procedi come segue:

  1. Assegna un nome alla casella di riepilogo (x: Name = " myListBox ")
  2. Aggiungi evento caricato per la finestra (Loaded = " Window_Loaded ")
  3. Implementa l'evento Loaded usando il metodo: ScrollToVerticalOffset

Ecco un esempio funzionante:

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

Altri suggerimenti

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

o

myListBox.SelectedIndex = midPoint

Dipende se vuoi che l'elemento centrale sia appena mostrato o selezionato.

Ho appena cambiato un codice bit di Zamboni e ho aggiunto il calcolo della posizione.

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

Non credo che ListBox lo abbia, ma ListViews ha il Metodo SecureVisible che sposta la barra di scorrimento nel punto necessario per assicurarsi che un elemento sia mostrato.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top