Showing posts with label Listbox. Show all posts
Showing posts with label Listbox. Show all posts

Tuesday, December 7, 2010

How to add “ScrollIntoView” to an ItemsControl

The ListBox control (in Silverlight or WPF) has a handy method called ScrollIntoView that forces a listbox scroll so that the parsed item is in view.  This post will describe how to add this capability to an ItemsControl.

Firstly, to enable vertical scrolling in an ItemsControl apply the following template.

<ItemsControl x:Name="myItemsControl">

    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Next, add the following class that extends the ItemsControl class with an overloaded “Scroll Into View” method.

using System.Windows;
using System.Windows.Controls;

namespace myNamespace {
    public static class Extensions {
        public static void ScrollIntoView(
this ItemsControl control,
object item) {
            FrameworkElement framework =
control.ItemContainerGenerator.ContainerFromItem(item)
as FrameworkElement;
            if (framework == null) { return; }
            framework.BringIntoView();
        }
        public static void ScrollIntoView(this ItemsControl control) {
            int count = control.Items.Count;
            if (count == 0) { return; }
            object item = control.Items[count - 1];
            control.ScrollIntoView(item);
        }
    }
}

With this extension you can force the ItemsControl to scroll to a specific item, or alternatively, using the overloaded method, simply scroll to the last item in the collection.  For example.

this.myItemsControl.ScrollIntoView();