其實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到數據源上,這樣通過修改綁定的數據源就可以實現數據驅動的滾動效果了。
