Sunday, May 4, 2014

ListBox.ScrollIntoView Not Working

Fought with this one for about 2 hours…hope this post will help someone not waste their time.

Working in a Windows 8.1 store app, I had a command responses from my quad come to my machine over a USB port that I wanted to behave as a auto-scrolling console.

As lines of text came in, I put them in an ObservableCollection<String> that was associated with the ItemsSource on the ListBox.

Then had the code:

DeviceConsole.UpdateLayout();
DeviceConsole.ScrollIntoView(_receivedItems.Last());

Where _receivedItems was my ObservableCollection<String>.

This didn’t work, after much troubleshooting, I realized that the some of the command responses where duplicated.  For example, “OK” was returned when I told it to do something.  This appeared many times in the list, so when _receivedItems.Last() returned “OK”, and ScrollIntoView(item) was called with “OK”, it simply looked for a string match for “OK”, not the particular instance of the string that was the last item in the list, and it just picked the first instance in the list and didn’t scroll it into view.

FIX

Once I determined what was happening, the fix was obvious.  I simply created a class similar to:

public class CommandResponses
{
     public int Index {get; set;}
     public String Respone {get; set:}
}

And used an instance of this class in my observable collection ObservableCollection<String> used to populated the ListBox.  As soon as I did this, DeviceConsole.ScrollIntoView(_receivedItems.Last()); worked like a champ!

This was on a Windows 8.1 store app, but I suspect the same scenarios apply to ListBoxs on other platforms as well

-twb

2 comments:

  1. You're a genius. You say you struggled with this for 2 hours. I have been on it for 2 days. I have read a hundred articles about ScrollIntoView() not working. I tried all their solutions but nothing worked and many of my own. When I read your solution I said "No that can't be it". But that was it. I can go home now. Thank you.

    ReplyDelete