WPF/개발

WPF ListView SelectedItem 자동 스크롤하는 방법

푸코잇 2024. 9. 20. 11:04

WPF ListView SelectedItem 자동 스크롤하는 방법에 대해 배워보자.

 

Behavior 생성

1. Microsoft.Xaml.Behaviors.Wpf Nuget 패키지 설치

WPF-Behaviors

 

2. ListView Behavior 생성

  • ListView의 Loaded, SelectionChanged 이벤트 발생 시 선택된 첫 번째 아이템으로 스크롤한다.
using Microsoft.Xaml.Behaviors;
using System.Collections;
using System.Windows;
using System.Windows.Controls;

namespace ListViewSelectedItemScroll
{
    public class ScrollToListViewSelectedItemBehavior : Behavior<ListView>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += OnLoaded;
            AssociatedObject.SelectionChanged += OnSelectionChanged;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Loaded -= OnLoaded;
            AssociatedObject.SelectionChanged -= OnSelectionChanged;
        }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ScrollToSelectedItem(sender);
        }
        private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ScrollToSelectedItem(sender);
        }

        private void ScrollToSelectedItem(object sender)
        {
            if (sender is ListView listView)
            {
                IList selectedItems = listView.SelectedItems;

                if (selectedItems.Count > 0)
                {
                    listView.ScrollIntoView(selectedItems[0]);
                }
            }
        }
    }
}

 

ListView Behavior 적용

<Window x:Class="ListViewSelectedItemScroll.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListViewSelectedItemScroll"
        mc:Ignorable="d"
        Title="ListView SelectedItem 자동 스크롤" Height="200" Width="400">
    <Grid>
        <ListView ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem}">
            <b:Interaction.Behaviors>
                <local:ScrollToListViewSelectedItemBehavior/>
            </b:Interaction.Behaviors>

            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

 

WPF-ListView-SelectedItem-Scroll

 

Name이 50인 Item을 SelectedItem으로 설정 후 실행하면 Loaded 이벤트가 발생해 자동 스크롤된다.

런타임에서 SelectedItem을 변경했을 경우 SelectionChanged 이벤트가 발생해 자동 스크롤된다.