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

时间:2015-05-27 14:06:34

标签: vb.net visual-studio-2012 scroll listbox listbox-control

我有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已被删除。

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

1 个答案:

答案 0 :(得分:3)

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

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有更多项目,您将在运行时获得异常。