8

I want to show the selected item in a list view automatically(it isn't possible to show all items without scrolling).

this.listView.SelectedIndex = 999; selects of course an item, but it doesn't show it.

what can I use to show it automatically ?

kind regards, jeff

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Jeffrey
  • 1,392
  • 4
  • 11
  • 18

4 Answers4

11

You can do this:-

listview.ScrollIntoView(listview.SelectedItem);

Scroll WPF ListBox to the SelectedItem set in code in a view model

Community
  • 1
  • 1
3

Update 2023 for .NET 5-7

Install a nuget package Microsoft.Xaml.Behaviors.Wpf, create a class like following:

using Microsoft.Xaml.Behaviors;
using System.Windows.Controls;
using System.Windows;

public class ScrollToSelectedListBoxItemBehavior: Behavior<ListBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectionChanged += AssociatedObjectOnSelectionChanged;
        AssociatedObject.IsVisibleChanged += AssociatedObjectOnIsVisibleChanged;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.SelectionChanged -= AssociatedObjectOnSelectionChanged;
        AssociatedObject.IsVisibleChanged -= AssociatedObjectOnIsVisibleChanged;
        base.OnDetaching();
    }

    private static void AssociatedObjectOnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        ScrollIntoFirstSelectedItem(sender);
    }

    private static void AssociatedObjectOnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ScrollIntoFirstSelectedItem(sender);
    }

    private static void ScrollIntoFirstSelectedItem(object sender)
    {
        if (!(sender is ListBox listBox)) 
            return;
        var selectedItems = listBox.SelectedItems;
        if (selectedItems.Count > 0)
            listBox.ScrollIntoView(selectedItems[0]);
    }
}

Moving to the XAML editor we need to add a single line:

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

Add this behavior class to ListView control:

<ListView ItemsSource="{Binding Items}">
    <i:Interaction.Behaviors>
        <local:ScrollToSelectedListBoxItemBehavior />
    </i:Interaction.Behaviors>
</ListView>
Andrei Krasutski
  • 4,913
  • 1
  • 29
  • 35
Sergey S
  • 889
  • 12
  • 18
  • This works like a charm. The new package for this is `Microsoft.Xaml.Behaviors.Wpf` as the `System.Windows.Interactivity.WPF` is depreciated. – Skint007 Apr 11 '22 at 03:11
1

Check out this one:
Scroll WPF Listview to specific line

Community
  • 1
  • 1
Yvo
  • 18,681
  • 11
  • 71
  • 90
-1

This might help you, i'm not sure if it's what you're looking for but it brings the selected item into view and scrolls to it for you if necessary.

 int selectedIndex = listView.Items.IndexOf((listView.SelectedItems[0]))

 listView.Items[selectedIndex].EnsureVisible();
David Swindells
  • 641
  • 1
  • 12
  • 28