Dan Sewell
Dan Sewell

Reputation: 1290

C# Scroll to top of listbox

Ive seen lots of posts which show how to scroll to bottom item of a ListBox, but cant work out how to autoscroll to the top of the listbox. If I scroll down my listbox, then use my filter function, the listbox will stay at the position you have scrolled down to, so the user may not see the results which are above where they are scrolled down to.

Ive been trying to use the listbox.ScrollIntoView but cannot get the right function. this is the context of where it would be... (commented part):

private void filter_Click(object sender, RoutedEventArgs e)
{
    string filterString = textBox1.Text;
    XElement _xml = XElement.Load("1/1.xml");
    {
        results.Items.Clear();
        foreach (XElement value in _xml.Elements("Operators").Elements("Operator"))
        {
            1Item _item = new 1Item();
            _item.TradingName = value.Element("TradingName").Value;

            if (_item.Town.IndexOf(filterString, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
            {
                results.Items.Add(_item);
                // add scroll function here
            }
        }
    } 
}

Many thanks.

Upvotes: 12

Views: 14509

Answers (3)

Ivan  Silkin
Ivan Silkin

Reputation: 485

One important notice to the @Bala-R 's answer (And why it did work for @Mr-Bungle) is that if you're calling the ScrollIntoView from another thread or component, you need to also invoke dispatcher:

    public async Task ScrollToTop()
    {
        await this.Dispatcher.BeginInvoke(() => {
            if (lstRecords.Items.Count > 0)
                lstRecords.ScrollIntoView(lstRecords.Items[0]);
        });
    }

Upvotes: 0

Peter Horsley
Peter Horsley

Reputation: 1756

ScrollIntoView didn't work for me, but this did:

VisualTreeHelperEx.FindDescendantByType<ScrollViewer>(YourListView)?.ScrollToTop();

This uses the Extended WPF Toolkit to get the ScrollViewer, but you can of course do it manually e.g. this answer.

Upvotes: 3

Bala R
Bala R

Reputation: 108937

if(results.Items.Count > 0)
    results.ScrollIntoView(results.Items[0]);

Upvotes: 32

Related Questions