프로그래밍/WPF

[WPF] ListView 또는 ListBox 에서 ScrollIntoView 사용법

흔한티벳여우 2022. 4. 15. 16:43
반응형

Behavior 클래스를 먼저 작성한다.

public static class ScrollToSelectedBehavior
{
    public static readonly DependencyProperty SelectedValueProperty =  DependencyProperty.RegisterAttached(
        "SelectedValue",
        typeof(object),
        typeof(ScrollToSelectedBehavior),
        new PropertyMetadata(null, OnSelectedValueChange));
    public static void SetSelectedValue(DependencyObject source, object value)
    {
        source.SetValue(SelectedValueProperty, value);
    }
    public static object GetSelectedValue(DependencyObject source)
    {
        return (object)source.GetValue(SelectedValueProperty);
    }
    private static void OnSelectedValueChange(DependencyObject d,  DependencyPropertyChangedEventArgs e)
    {
        var listView = d as ListView;
        listView.ScrollIntoView(e.NewValue);
    }
}

 

xaml에서 사용할때는 아래와 같이 사용한다.

<ListView SelectedIndex="{Binding SizeListViewSelectedIndex,  Mode=TwoWay}"
          behavior:ScrollToSelectedBehavior.SelectedValue="{Binding  Path=SelectedValue, RelativeSource={RelativeSource Self}}"
          ItemsSource="{Binding SizeSelectionLists}"
          ScrollViewer.HorizontalScrollBarVisibility="Hidden"
          ScrollViewer.VerticalScrollBarVisibility="Hidden">
반응형