I currently have a list box set up as follows:
.xaml:
<ListBox Name="DetailsList" ItemsSource="{Binding}" LayoutUpdated="DetailsList_LayoutUpdated" />
.xaml.cs:
private ObservableCollection<string> details = new ObservableCollection<string>();
In the window constructor:
DetailsList.DataContext = details;
I had a button that did the following:
details.Add(System.DateTime.Now.ToString("HH:mm:ss ") + someString);
DetailsList.UpdateLayout();
var lastItem = DetailsList.Items[DetailsList.Items.Count - 1];
DetailsList.SelectedItem = lastItem;
DetailsList.ScrollIntoView(lastItem);
That should select the last item in the list and scroll to it, but it only does it around 75% of the time. Instead, it will often select the second last and scroll to that instead.
I tried moving the scroll and selection into a LayoutUpdated event handler, no change.
I tried two separate buttons – one to add, one to select and scroll. If I add one item at a time then scroll, it seems to be slightly more reliable – it works 90% of the time. If I add half a dozen items before scrolling, it almost never works. It will typically select one of the new items, but not the last one.
Am I doing something wrong, or is there a bug with System.Windows.Controls.ListBox?
The problem is that multiple items with the same string value have been added to the list. When setting the
SelectedItemproperty on theListViewit will call theEqualsmethod to find the correct item. It will select the first item for whichEqualsreturns true which is why you’re getting the observed behaviour.You need to add unique strings (e.g. add milliseconds) or wrap them in another class to be able to uniquely identify them.