[WPF] Auto Scroll Behavior for ListBox

By | October 25, 2013

Advertisement from Google

If you want scroll ListBox to the end automatically when new item added in ItemsSource collection you could use following attached behavior. This approach perfectly suit for MVVM way.

ListBoxBehavior.cs:

using System.Windows;

namespace ListBoxBehavior
{
    /// <summary>
    /// ListBox AutoScroll attached properties
    /// </summary>
    public static class ListBoxBehavior
    {
        public static readonly DependencyProperty AutoScrollProperty = DependencyProperty.RegisterAttached(
            "AutoScroll",
            typeof(bool),
            typeof(System.Windows.Controls.ListBox),
            new PropertyMetadata(false));

        public static readonly DependencyProperty AutoScrollHandlerProperty =
            DependencyProperty.RegisterAttached(
                "AutoScrollHandler",
                typeof(AutoScrollHandler),
                typeof(System.Windows.Controls.ListBox));

        public static bool GetAutoScroll(System.Windows.Controls.ListBox instance)
        {
            return (bool)instance.GetValue(AutoScrollProperty);
        }

        public static void SetAutoScroll(System.Windows.Controls.ListBox instance, bool value)
        {
            AutoScrollHandler OldHandler = (AutoScrollHandler)instance.GetValue(AutoScrollHandlerProperty);
            if (OldHandler != null)
            {
                OldHandler.Dispose();
                instance.SetValue(AutoScrollHandlerProperty, null);
            }

            instance.SetValue(AutoScrollProperty, value);
            if (value)
            {
                instance.SetValue(AutoScrollHandlerProperty, new AutoScrollHandler(instance));
            }
        }
    }
}

AutoScrollHandler.cs:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Data;

namespace ListBoxBehavior
{
    /// <summary>
    /// Handle auto scroll functionality
    /// </summary>
    public class AutoScrollHandler : DependencyObject, IDisposable
    {
        public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
            "ItemsSource",
            typeof(IEnumerable),
            typeof(AutoScrollHandler),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.None,
                ItemsSourcePropertyChanged));

        private System.Windows.Controls.ListBox target;

        public AutoScrollHandler(System.Windows.Controls.ListBox target)
        {
            this.target = target;
            var binding = new Binding("ItemsSource") { Source = this.target };
            BindingOperations.SetBinding(this, ItemsSourceProperty, binding);
        }

        public void Dispose()
        {
            BindingOperations.ClearBinding(this, ItemsSourceProperty);
        }

        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { this.SetValue(ItemsSourceProperty, value); }
        }

        private static void ItemsSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((AutoScrollHandler)o).ItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
        }

        private void ItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            var collection = oldValue as INotifyCollectionChanged;
            if (collection != null)
            {
                collection.CollectionChanged -= this.CollectionChangedEventHandler;
            }

            collection = newValue as INotifyCollectionChanged;
            if (collection != null)
            {
                collection.CollectionChanged += this.CollectionChangedEventHandler;
            }
        }

        private void CollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems == null || e.NewItems.Count < 1)
            {
                return;
            }

            this.target.ScrollIntoView(e.NewItems[e.NewItems.Count - 1]);
        }
    }
}

Also you could download compiled .Net 4.0 ListBoxBehavior.dll assembly (see links below) and use it like this:

Add xml namespace:

xmlns:listBoxBehavior="clr-namespace:ListBoxBehavior;assembly=ListBoxBehavior"

Advertisement from Google

And use it with ListBox:

<ListBox ItemsSource="{Binding Items}" ListBoxBehavior:ListBoxBehavior.AutoScroll="True" />

Assembly: ListBoxBehavior.dll

Namespace: ListBoxBehavior

.Net Framework: 4.0

Download

binary (ListBoxBehavior.dll)

License:

Copyright 2013 Ivan Derevianko

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

3 thoughts on “[WPF] Auto Scroll Behavior for ListBox

  1. Luke

    Thanks for this.

    Has a xaml error AutoScroll / AutoScrollHandler is already registered by ListBox

    Can fix by ensuring that the ownertype of the dependency properties are set to AutoScrollHandler

    public static class ListBoxBehavior
    {
    public static readonly DependencyProperty AutoScrollProperty = DependencyProperty.RegisterAttached(
    “AutoScroll”,
    typeof(bool),
    typeof(AutoScrollHandler),
    new PropertyMetadata(false));

    public static readonly DependencyProperty AutoScrollHandlerProperty =
    DependencyProperty.RegisterAttached(
    “AutoScrollHandler”,
    typeof(AutoScrollHandler),
    typeof(AutoScrollHandler));

    Also to use in your view simple add
    xmlns:mvvmBehaviors=”clr-namespace:Interface.Behaviours”>

    then Set the property with
    <ListView mvvmBehaviors:ListBoxBehavior.AutoScroll="True"

    Reply
  2. vertex

    I doesn’t work if the items have the same string values

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *