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:


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.


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


No comments:

Post a Comment