Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Scroll to top of listbox

Tags:

c#

wpf

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.

like image 995
Dan Sewell Avatar asked Feb 22 '11 20:02

Dan Sewell


2 Answers

if(results.Items.Count > 0)
    results.ScrollIntoView(results.Items[0]);
like image 152
Bala R Avatar answered Nov 15 '22 19:11

Bala R


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.

like image 30
Mr. Bungle Avatar answered Nov 15 '22 18:11

Mr. Bungle