WPF ListBox implement autoscroll via behavior extension and SelectedItem
public class ListBoxAutoScrollBehavior : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged; base.OnAttached(); } private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e) { var lbx = sender as ListBox; if (lbx != null && lbx.SelectedItem != null) { lbx.ScrollIntoView(lbx.SelectedItem); } } protected override void OnDetaching() { AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged; base.OnDetaching(); } } <behavior:Interaction.Behaviors> <local:ListBoxAutoScrollBehavior/> </behavior:Interaction.Behaviors> <ListBox.ContextMenu> private void InitTimer() { System.Timers.Timer tmr = new System.Timers.Timer(); tmr.Interval = 1000; tmr.Elapsed += Tmr_Elapsed; tmr.Enabled = true; } private void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if(++SelectedIdx>=booksCount) { SelectedIdx = 0; } SelectedBk = BooksCollection[SelectedIdx]; }
//xaml <Window x:Class="WpfApp38.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors" WindowState="Maximized" xmlns:local="clr-namespace:WpfApp38" mc:Ignorable="d" Title="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="450" Width="800"> <Window.Resources> <Style TargetType="{x:Type TextBlock}" x:Key="tbkStyle"> <Setter Property="HorizontalAlignment" Value="Stretch"/> <Setter Property="VerticalAlignment" Value="Center"/> <Setter Property="FontSize" Value="30"/> <Setter Property="Foreground" Value="Red"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="FontSize" Value="50"/> <Setter Property="FontWeight" Value="ExtraBold"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedIndex="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.CacheLength="1" VirtualizingPanel.CacheLengthUnit="Item" > <behavior:Interaction.Behaviors> <local:ListBoxAutoScrollBehavior/> </behavior:Interaction.Behaviors> <ListBox.ContextMenu> <ContextMenu> <MenuItem Header="Export All" Command="{Binding ExportAllCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/> <MenuItem Header="Mark All Selected" Command="{Binding MarkAllSelected}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/> </ContextMenu> </ListBox.ContextMenu> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox Content="IsSelected" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="30" IsChecked="{Binding ISSTEM}" IsThreeState="False"/> <TextBlock Text="{Binding Id}" Style="{StaticResource tbkStyle}"/> <TextBlock Text="{Binding ISBN}" Style="{StaticResource tbkStyle}" /> <Border Width="500" Height="500" BorderThickness="3" BorderBrush="Black" > <Border.Background> <ImageBrush ImageSource="{Binding ImgSource}" RenderOptions.BitmapScalingMode="Fant" RenderOptions.EdgeMode="Aliased"/> </Border.Background> </Border> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> //cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data.SqlTypes; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Xaml.Behaviors; using Newtonsoft.Json; namespace WpfApp38 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var vm = new BookVM(); this.DataContext = vm; } } public class BookVM : INotifyPropertyChanged { public BookVM() { InitData(); InitCommands(); } private void InitTimer() { System.Timers.Timer tmr = new System.Timers.Timer(); tmr.Interval = 1000; tmr.Elapsed += Tmr_Elapsed; tmr.Enabled = true; } private void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if(++SelectedIdx>=booksCount) { SelectedIdx = 0; } SelectedBk = BooksCollection[SelectedIdx]; } private void InitCommands() { ExportAllCommand = new DelCommand(ExportAllCommandExecuted); MarkAllSelected = new DelCommand(MarkAllSelectedExecuted); } private void MarkAllSelectedExecuted(object obj) { var books = ((System.Collections.IList)(obj as ListBox).ItemsSource)?.Cast<Book>()?.ToList(); if (books != null && books.Any()) { booksCount = books.Count; for (int i = 0; i < booksCount; i++) { books[i].ISSTEM = true; } MessageBox.Show("Mark all as Selected!"); } } private void ExportAllCommandExecuted(object obj) { var books = ((System.Collections.IList)(obj as ListBox))?.Cast<Book>()?.ToList(); if (books != null && books.Any()) { string jsonStr = JsonConvert.SerializeObject(books, Formatting.Indented); string jsonFile = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}json.json"; File.WriteAllText(jsonFile, jsonStr); MessageBox.Show($"Exported in {jsonFile}", "Export"); } } private void InitData() { var imgs = Directory.GetFiles(@"../../Images"); if (imgs != null && imgs.Any()) { int imgsCount = imgs.Count(); BooksCollection = new ObservableCollection<Book>(); for (int i = 0; i < 100000; i++) { BooksCollection.Add(new Book() { Id = i + 1, ISBN = $"ISBN_{i + 1}", ISSTEM = (i % 5 == 0) ? true : false, ImgSource = GetImgSourceViaUrl(imgs[i % imgsCount]) }); } booksCount=BooksCollection.Count; } InitTimer(); } private ImageSource GetImgSourceViaUrl(string url) { BitmapImage bmi = new BitmapImage(); bmi.BeginInit(); bmi.UriSource = new Uri(url, UriKind.RelativeOrAbsolute); bmi.EndInit(); if (bmi.CanFreeze) { bmi.Freeze(); } return bmi; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } private ObservableCollection<Book> booksCollection; public ObservableCollection<Book> BooksCollection { get { return booksCollection; } set { if (value != booksCollection) { booksCollection = value; OnPropertyChanged(nameof(BooksCollection)); } } } private int selectedIdx; public int SelectedIdx { get { return selectedIdx; } set { if (value != selectedIdx) { selectedIdx = value; OnPropertyChanged(nameof(SelectedIdx)); } } } private Book selectedBk; public Book SelectedBk { get { return selectedBk; } set { if(value!=selectedBk) { selectedBk = value; OnPropertyChanged(nameof(SelectedBk)); } } } private int booksCount { get; set; } = 0; public DelCommand ExportAllCommand { get; set; } public DelCommand MarkAllSelected { get; set; } } public class ListBoxAutoScrollBehavior : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged; base.OnAttached(); } private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e) { var lbx = sender as ListBox; if (lbx != null && lbx.SelectedItem != null) { lbx.ScrollIntoView(lbx.SelectedItem); } } protected override void OnDetaching() { AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged; base.OnDetaching(); } } public class Book { public int Id { get; set; } public bool ISSTEM { get; set; } public string ISBN { get; set; } public ImageSource ImgSource { get; set; } } public class DelCommand : ICommand { private Action<object> execute; private Predicate<object> canExecute; public DelCommand(Action<Object> executeValue, Predicate<object> canExecuteValue = null) { execute = executeValue; canExecute = canExecuteValue; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { if (canExecute == null) { return true; } return canExecute(parameter); } public void Execute(object parameter) { execute(parameter); } } }