WPF中ListView滾動到當前行的幾種方法


其實ListBox和ListView在這里是一樣的。

1、使用方法ScrollIntoView

ListView繼承自ListBox,ListBox有這個方法,可以滾動到指定的item。

listBox.ScrollIntoView(listBox.Items[listBox.Items.Count - 1]);//移動到最后一行

使用的時候需要給控件加上x:Name。如果要用數據驅動的話,感覺上直接后台調用前台的控件是不太合適的。所以有第二種方法Behavior。

2、使用Behavior

上鏈接:https://github.com/microsoft/XamlBehaviorsWpf

引入命名空間

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

在ListView下使用

<behaviors:Interaction.Behaviors>
    <local:AutoScrollBehavior />
</behaviors:Interaction.Behaviors> 

類的實現

    public class AutoScrollBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
        void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ListBox listBox)
            {
                if (listBox.SelectedItem != null)
                {
                    listBox.Dispatcher.BeginInvoke((Action)delegate
                    {
                        listBox.UpdateLayout();
                        listBox.ScrollIntoView(listBox.SelectedItem);//在這里使用一的方法
                    });
                }
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.SelectionChanged -= new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
    }

ListBox控件需要綁定SelectedItem到數據源上,這樣通過修改綁定的數據源就可以實現數據驅動的滾動效果了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM