WPF ListBox scroll to selected item automatically via behavior

1.Install Microsoft.Xaml.Behaviors.Wpf

2.

//xaml
<Window x:Class="WpfApp194.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"
        xmlns:local="clr-namespace:WpfApp194"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="lbx">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Height" Value="30"/>
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Red"/>
                            <Setter Property="Foreground" Value="Red"/>
                            <Setter Property="Height" Value="70"/>
                            <Setter Property="FontSize" Value="50"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ListBox.ItemContainerStyle>
            <behavior:Interaction.Behaviors>
                <local:ListBoxAutoScrollToSelectedItemBehavior/>
            </behavior:Interaction.Behaviors>
        </ListBox>
    </Grid>
</Window>



//xaml.cs
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp194
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitLbx();
        }

        private Random rnd;
        private int selectedIdx;

        private System.Timers.Timer tmr;
        private void InitLbx()
        {
            lbx.Items.Clear();
            for(int i=0;i<100;i++)
            {
                lbx.Items.Add($"Item_{i}");
            }

            if (tmr == null)
            {
                tmr = new System.Timers.Timer();
                tmr.Interval = 1000;
                tmr.Elapsed += Tmr_Elapsed;
                tmr.Start();
            }

            if(rnd==null)
            {
                rnd=new Random();
            }
        }

        private void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            selectedIdx = rnd.Next(0, 100);            
            Application.Current?.Dispatcher.BeginInvoke(new Action(() =>
            {
                lbx.SelectedItem=lbx.Items[selectedIdx];
                lbx.ScrollIntoView(lbx.SelectedItem);
                this.Title = $"{selectedIdx}";
            }));            
        }
    }

    public class ListBoxAutoScrollToSelectedItemBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
        }


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

        private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (AssociatedObject.SelectedItem != null)
            {
                Application.Current?.Dispatcher.BeginInvoke(new Action(() =>
                {
                    AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItem);
                }));
            }
        }
    }   
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2025-04-04 18:44  FredGrit  阅读(25)  评论(0)    收藏  举报