Question

Puis-je définir par programme la position d'une barre de défilement WPF ListBox? Par défaut, je veux qu'il soit placé au centre.

Était-ce utile?

La solution

Pour déplacer la barre de défilement verticale dans un contrôle ListBox, procédez comme suit:

  1. Nommez votre zone de liste (x: Name = "myListBox")
  2. Ajouter un événement chargé pour la fenêtre (Loaded = "Window_Loaded")
  3. Implémenter un événement chargé à l'aide de la méthode: ScrollToVerticalOffset

Voici un exemple de travail:

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

Autres conseils

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

ou

myListBox.SelectedIndex = midPoint

Cela dépend si vous voulez que l'élément du milieu soit simplement affiché ou sélectionné.

Je viens de changer un code de bit de Zamboni et d'ajouter un calcul de position.

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

Je ne pense pas que ListBox l’ait, mais ListViews a le EnsureVisible est une méthode qui déplace la barre de défilement à l'emplacement requis pour s'assurer de la présence d'un élément.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top