如何使用垂直滚动条控制两个列表框

本文关键字:两个 列表 何使用 垂直 滚动条 控制 | 更新日期: 2023-09-27 18:20:53

我有一个Windows窗体,里面有6个列表框。

我正试图找到/制作一个代码,让它们一起滚动。所以我在表格上放了一个垂直滚动条,然后输入以下代码:

private void vScrollR_Scroll(object sender, ScrollEventArgs e)
{
    int i = vScrollR.Value;
    lstcr1.SelectedIndex = i;
    lstpr1.SelectedIndex = i;
    lstsr1.SelectedIndex = i;
    lstcr2.SelectedIndex = i;
    lstpr2.SelectedIndex = i;
    lstsr2.SelectedIndex = i;
}

但由于某种原因,它不起作用(我总是返回0)。我是不是搞错了?还有其他方法可以实现我想要的吗?也许,我首先需要一种方法?

非常感谢所有将要回答的人。

如何使用垂直滚动条控制两个列表框

将SelectedIndex更改为TopIndex。我刚试过这个,效果很好。

要在更新时保持UI同步,可以使用Control.BeginUpdate和Control.EndUpdate

        listBox1.BeginUpdate();
        listBox2.BeginUpdate();
        listBox1.TopIndex = 
        listBox2.TopIndex = ++x;
        listBox1.EndUpdate();
        listBox2.EndUpdate();

尝试创建一个从Listbox继承的独立类。

我希望这对你有帮助。

using System;
using System.Windows.Forms;
public class myScrollingListBox : ListBox 
{
  // Event declaration
  public delegate void myScrollingListBoxDelegate(object Sender, myScrollingListBoxScrollArgs e);
  public event myScrollingListBoxDelegate Scroll;
  // WM_VSCROLL message constants
  private const int WM_VSCROLL = 0x0115;
  private const int SB_THUMBTRACK = 5;
  private const int SB_ENDSCROLL = 8;
  protected override void WndProc(ref Message m) 
  {
    // Trap the WM_VSCROLL message to generate the Scroll event
    base.WndProc(ref m);
    if (m.Msg == WM_VSCROLL)
    {
      int nfy = m.WParam.ToInt32() & 0xFFFF;
      if (Scroll != null && (nfy == SB_THUMBTRACK || nfy == SB_ENDSCROLL))
        Scroll(this, new myScrollingListBoxScrollArgs(this.TopIndex, nfy == SB_THUMBTRACK));
    }
  }
  public class myScrollingListBoxScrollArgs 
  {
    // Scroll event argument
    private int mTop;
    private bool mTracking;
    public myScrollingListBoxScrollArgs(int top, bool tracking)
    {
      mTop = top;
      mTracking = tracking;
    }
    public int Top
    {
      get { return mTop; }
    }
    public bool Tracking
    {
      get { return mTracking; }
    }
  }
}