【问题标题】:Preventing ListBox scrolling to top when updated更新时防止 ListBox 滚动到顶部
【发布时间】:2010-05-22 18:04:49
【问题描述】:

我正在尝试使用 ListBox 播放列表构建一个简单的音乐播放器。将音频文件添加到播放列表时,它首先用文件名填充 ListBox,然后(在单独的线程上)提取 ID3 数据并用正确的艺术家 - 标题信息覆盖文件名(很像 Winamp)。

但是当 ListBox 被更新时,它是不可滚动的,因为它总是在每次覆盖时跳到顶部。

有什么办法防止这种情况发生?

编辑:
代码:

public Form1()
{
    //Some initialization code omitted here

    BindingList<TAG_INFO> trackList = new BindingList<TAG_INFO>();

    // The Playlist
    this.playlist = new System.Windows.Forms.ListBox();
    this.playlist.Location = new System.Drawing.Point(12, 12);
    this.playlist.Name = "playlist";
    this.playlist.Size = new System.Drawing.Size(229, 316);
    this.playlist.DataSource = trackList;
}

private void playlist_add_Click(object sender, EventArgs e)
{
    //Initialize OpenFileDialog
    OpenFileDialog opd = new OpenFileDialog();
    opd.Filter = "Music (*.WAV; *.MP3; *.FLAC)|*.WAV;*.MP3;*.FLAC|All files (*.*)|*.*";
    opd.Title = "Select Music";
    opd.Multiselect = true;

    //Open OpenFileDialog
    if (DialogResult.OK == opd.ShowDialog())
    {

        //Add opened files to playlist
        for (int i = 0; opd.FileNames.Length > i; ++i)
        {
            if (File.Exists(opd.FileNames[i]))
            {
                trackList.Add(new TAG_INFO(opd.FileNames[i]));
            }
        }

        //Initialize BackgroundWorker
        BackgroundWorker _bw = new BackgroundWorker();
        _bw.WorkerReportsProgress = true;
        _bw.DoWork += new DoWorkEventHandler(thread_trackparser_DoWork);
        _bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged);

        //Start ID3 extraction
        _bw.RunWorkerAsync();
    }

}

void thread_trackparser_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker _bw = sender as BackgroundWorker;

    for (int i = 0; i < trackList.Count; ++i)
    {
        //Pass extracted tag info to _bw_ProgressChanged for thread-safe playlist entry update
        _bw.ReportProgress(0,new object[2] {i, BassTags.BASS_TAG_GetFromFile(trackList[i].filename)});
    }
}

void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    object[] unboxed = e.UserState as object[];

    trackList[(int)unboxed[0]] = (unboxed[1] as TAG_INFO);
}

EDIT2:
更简单的测试用例:
尝试向下滚动而不选择项目。变化中的 ListBox 将再次滚动到顶部。

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class Form1 : Form
    {
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();

            // listBox1
            this.listBox1.FormattingEnabled = true;
            this.listBox1.Location = new System.Drawing.Point(0, 0);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(200, 290);

            // timer1
            this.timer1.Enabled = true;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(200, 290);
            this.Controls.Add(this.listBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
        }

        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.Timer timer1;

        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 45; i++)
                listBox1.Items.Add(i);
        }

        int tickCounter = -1;

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (++tickCounter > 44) tickCounter = 0;
            listBox1.Items[tickCounter] = ((int)listBox1.Items[tickCounter])+1;
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

【问题讨论】:

  • 你能发布一些代码吗?它的更新方式可能与问题有关。
  • 添加了用于演示相同问题的更简单的代码。

标签: c# winforms listbox


【解决方案1】:

很好的重现代码,我可以毫无问题地诊断出问题的根源。这是一个功能,而不是一个错误。按几次向下箭头键,然后滚动列表。请注意,它现在不会跳回。

这里发生的事情是,列表框会在更新时自动将具有焦点的项目滚动回视图中。这通常是可取的行为,您不能将其关闭。当您像这样更新列表时,解决方法(例如选择要更新的项目)不会很漂亮,它会严重闪烁。可能是虚拟模式,我没试过。

ListView 没有这种行为,请考虑改用它。使用 View = List 或 Details。

【讨论】:

【解决方案2】:

在进行更新时禁用列表框的任何绘制可能是谨慎的做法。使用 ListBox.BeginUpdate() 然后更新条目,完成后调用 ListBox.EndUpdate()。这应确保在更新期间不会发生刷新。

您还应该确保不要从线程刷新 ListBox,因为不允许跨线程,并且运行时将显示一条消息,指出发生了“跨线程异常”。

使用 ListBox 的 BeginInvoke(...) 方法来解决跨线程问题。请参阅 MSDN 上的 here 了解如何完成此操作。

【讨论】:

    【解决方案3】:

    是的,.BeginUpdate() 是一个很好的解决方案:

    公开课表1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Start()
    
    End Sub
    Dim ix As Integer
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    
        ix = ListBox1.TopIndex
        Label1.Text = ListBox1.TopIndex     'get most top displayed in the listbox
        ListBox1.BeginUpdate()              'do not refresh during update
        ListBox1.Items.Clear()              'do updates
        For i = 1 To 100
            ListBox1.Items.Add(i.ToString & "." & Int((101) * Rnd()).ToString)
        Next
        ListBox1.TopIndex = ix              'set the top item to be displayed
        ListBox1.EndUpdate()                'refresh the listbox
    
    End Sub
    
    Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) _
    Handles VScrollBar1.Scroll
        VScrollBar1.Maximum = ListBox1.Items.Count
        ListBox1.TopIndex = VScrollBar1.Value       ' link another scrollbar if you want
        Label2.Text = VScrollBar1.Value
    
    End Sub
    

    结束类

    代码自己说话。计时器正在生成随机数。数字填充在列表框中。在更新之前,只需阅读列表框的当前顶部索引。在更新期间,通过 Begin Update 关闭渲染。然后恢复 Top Index 并调用 End Update。

    我放了一个额外的滚动条,链接到列表框。

    【讨论】:

    • 谢谢。 TopIndex 为我解决了。 Begin/EndUpdate 使刷新更加“顺畅”。
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    相关资源
    最近更新 更多