#992 – Scrolling an Item in a ListBox into View

You can programmatically scroll an item in a ListBox into view by using the ListBox.ScrollIntoView method.

In the example below, we scroll the actor Jane Wyman into view when the user clicks the button.

        <ListBox Name="lbActors" Margin="15,5" Width="200" Height="150"
                 ItemsSource="{Binding ActorList}"
                 DisplayMemberPath="NameAndDates"/>
        <Button Content="Find Jane Wyman" Margin="10"
                Click="btnFindJane_Click"/>

992-001

In the Click event handler for the button, we use Linq to find the Actor object for Jane Wyman and we then call ScrollIntoView.

        private void btnFindJane_Click(object sender, RoutedEventArgs e)
        {
            Actor jane = (from a in ActorList
                         where a.FirstName == "Jane"
                            && a.LastName == "Wyman"
                         select a).First();
            lbActors.ScrollIntoView(jane);
            lbActors.SelectedItem = jane;
        }

992-002

Advertisements