sokolovic
sokolovic

Reputation: 293

WPF ListBox - Scroll always on top

I have a ListBox that displays some words. Words are entered in TextBox, and when submitted on button click, they are added to ListBox. The problem is, if I add many words, scroll is always on top of ListBox, so I don't see last but first words added. Is there a way to dynamically move scroll to the end of ListBox every time word is added, so last added word is visible?

Upvotes: 1

Views: 1388

Answers (1)

Muad'Dib
Muad'Dib

Reputation: 29266

here you go, this should do nicely...

public static void ScrollToBottom(this ListBox listbox)
{
    if (listbox == null) throw new ArgumentNullException("listbox", "Argument listbox cannot be null");
    if (!listbox.IsInitialized) throw new InvalidOperationException("ListBox is in an invalid state: IsInitialized == false");

    if (listbox.Items.Count == 0)
        return;

    listbox.ScrollIntoView(listbox.Items[listbox.Items.Count - 1]);
}

Now, given any ListBox I can do this: ListBox lb = ...;

lb.ScrollToBottom();

Upvotes: 1

Related Questions