将 2 个列表框同步到 1 个滚动条

Sync 2 list boxes to 1 scrollbar

我有 2 个彼此相邻的列表框。一个持有订单,另一个持有订单的总成本。

出于显而易见的原因,我需要两个列表框同时滚动。

这是我试过的方法

Private Sub lstOrders_Scroll()
    lstTotalsEachOrder.TopIndex = lstOrders.TopIndex
End Sub

Private Sub lstTotalsEachOrder_Scroll()
    lstOrders.TopIndex = lstTotalsEachOrder.TopIndex
End Sub

如有任何帮助,我们将不胜感激。

我正在使用 Visual Studio 2012 并且我在 vb 中编码。

根据我的阅读,_Scroll 已被删除。

我在想我可以删除订单列表框上的滚动条并通过总计列表框上的滚动条控制两个框。

如果你想保持所选索引同步,那么你可以这样做:

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

但是要使实际滚动同步,您需要自己绘制列表框项目。下面完成这个任务,但是滚动父级 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 有更多项目,您将在运行时遇到异常。