如果您想保持选定的索引同步,那么您可以这样做:
Option Strict On
Option Explicit On
Public Class Form1
Private Sub ListBox_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim parentListBox As ListBox = DirectCast(sender, ListBox)
Dim childListBox As ListBox = DirectCast(parentListBox.Tag, ListBox)
If parentListBox.SelectedIndex < childListBox.Items.Count Then
childListBox.SelectedIndex = parentListBox.SelectedIndex
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.ListBox1.Tag = Me.ListBox2
Me.ListBox2.Tag = Me.ListBox1
AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox_SelectedIndexChanged
AddHandler ListBox2.SelectedIndexChanged, AddressOf ListBox_SelectedIndexChanged
End Sub
End Class
但是,要使实际滚动同步,您需要自己绘制列表框项目。下面完成了这个任务,但是滚动 parent 真的很慢listbox
。
Option Strict On
Option Explicit On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.ListBox1.DrawMode = DrawMode.OwnerDrawFixed
Me.ListBox2.DrawMode = DrawMode.OwnerDrawFixed
Me.ListBox1.Tag = Me.ListBox2
Me.ListBox2.Tag = Me.ListBox1
AddHandler Me.ListBox1.DrawItem, AddressOf ListBox_DrawItem
AddHandler Me.ListBox2.DrawItem, AddressOf ListBox_DrawItem
End Sub
Private Sub ListBox_DrawItem(sender As Object, e As DrawItemEventArgs)
Dim parentListBox As ListBox = DirectCast(sender, ListBox)
Dim childListBox As ListBox = DirectCast(parentListBox.Tag, ListBox)
e.DrawBackground()
e.DrawFocusRectangle()
Dim brsh As New SolidBrush(Color.Black)
If String.Compare(e.State.ToString, DrawItemState.Selected.ToString) > 0 Then brsh.Color = Color.White
e.Graphics.DrawString(CStr(parentListBox.Items(e.Index)), e.Font, brsh, New RectangleF(e.Bounds.Location, e.Bounds.Size))
childListBox.TopIndex = parentListBox.TopIndex
End Sub
End Class
另请注意,没有错误检查以确保项目实际上可以滚动到,因此如果listbox
有更多项目,您将在运行时收到异常。