// Update list based on selection. // Return true if there's an exact match, or false if not. static bool SelectListItem(ListBox list, object value) { ItemCollection itemList = list.Items; // Perform a binary search for the item. int first = 0; int limit = itemList.Count; while (first < limit) { int i = first + (limit - first) / 2; var item = (IComparable)(itemList[i]); int comparison = item.CompareTo(value); if (comparison < 0) { // Value must be after i first = i + 1; } else if (comparison > 0) { // Value must be before i limit = i; } else { // Exact match; select the item. list.SelectedIndex = i; itemList.MoveCurrentToPosition(i); list.ScrollIntoView(itemList[i]); return true; } } // Not an exact match; move current position to the nearest item but don't select it. if (itemList.Count > 0) { int i = Math.Min(first, itemList.Count - 1); itemList.MoveCurrentToPosition(i); list.ScrollIntoView(itemList[i]); } return false; }
void MoveListPosition(ListBox listBox, int distance) { int i = listBox.Items.CurrentPosition + distance; if (i >= 0 && i < listBox.Items.Count) { listBox.Items.MoveCurrentToPosition(i); listBox.SelectedIndex = i; listBox.ScrollIntoView(listBox.Items[i]); } }
public void OnPositionChanged(ListBox listBox, TimeSpan position) { var lyrics = LyricModel; if (lyrics != null && lyrics.Lyrics != null) { var selected = lyrics.BeforeOrAt(position); if (selected != null) { listBox.SelectedItem = selected; var display = lyrics.Lyrics.SkipWhile(o => o != selected).Skip(3).FirstOrDefault(); if (display != null) listBox.ScrollIntoView(display); else listBox.ScrollIntoView(selected); } } }