如何正确地用代码设置ListBox的当前选中项

2025-03-04 21:48:31
推荐回答(2个)
回答1:

Private Sub RemoveTopItems()
   ' Determine if the currently selected item in the ListBox 
   ' is the item displayed at the top in the ListBox.
   If listBox1.TopIndex <> listBox1.SelectedIndex Then
      ' Make the currently selected item the top item in the ListBox.
      listBox1.TopIndex = listBox1.SelectedIndex
   End If
   ' Remove all items before the top item in the ListBox.
   Dim x As Integer
   For x = listBox1.SelectedIndex - 1 To 0 Step -1
      listBox1.Items.RemoveAt(x)
   Next x

   ' Clear all selections in the ListBox.
   listBox1.ClearSelected()
End Sub 'RemoveTopItems

listBox1.SelectedIndex 设置选中的项!

回答2:

一开始使用的是PreviewMouseDown解决,在MouseDown的时候,通过DataContext也好,通过FindAncestor也好,反正是在获得焦点的同时选择上了。 但是随着项目的进行,这种方法造成DataBinding的Validation出现了问题。Validation应该是在LostFocus是