【问题标题】:How to embed ProgressBar into a ListView without WPF?如何在没有 WPF 的情况下将 ProgressBar 嵌入到 ListView 中?
【发布时间】:2013-09-15 11:30:34
【问题描述】:

我发现的所有互联网资源都声称,在WinForms 中,实现这一目标的唯一可能性是创建自己的UserControl(例如:hereherehereand here)。

是否可以仅使用提供的WinForms 控件来实现此目的?

【问题讨论】:

    标签: c# .net winforms listview progress-bar


    【解决方案1】:

    是的,有可能:

    • 创建一个ImageList 并为列表中的每个项目添加一个Bitmap
    • 创建ListView 并将上面创建的ImageList 附加为SmallImageList
    • ListView 样式设置为Details
    • 根据需要添加尽可能多的列 - 第一个必须包含图片
    • 添加后续ListViewItems,为每列添加适当的字符串,并适当的ImageIndex引用在第一步中创建的适当的Bitmap

     

    //...
    {
      foreach (/*item to add to list*/)
      {
        Bitmap progressBarBitmap = new Bitmap(
            this.imageList.ImageSize.Width,
            this.imageList.ImageSize.Height);
        this.imageList.Images.Add(progressBarBitmap);
        ProgressBar progressBar = new ProgressBar();
        progressBar.MinimumSize = this.imageList.ImageSize;
        progressBar.MaximumSize = this.imageList.ImageSize;
        progressBar.Size = this.imageList.ImageSize;
    
        // probably create also some BackgroundWorker here with information about
        // this particular progressBar
    
        ListViewItem lvi = new ListViewItem(
            new[] { "column1", ... },
            this.listView.Items.Count);
    
        lvi.UseItemStyleForSubItems = true;
        this.listView.Items.Add(lvi);
        lvi.Tag = /* some convenient info class to refer back to related objects */
      }
    //...
    }
    
    • 刷新ProgressBar:

     

    int previousProgress = progressBar.Value;
    progressBar.Value = ...
    if (progressBar.Value != previousProgress)
    {
      progressBar.DrawToBitmap(progressBarBitmap, bounds);
      progressBarImageList.Images[index] = progressBarBitmap;
    }
    

    其中progressBarBitmapprogressBarImageList 中相应progressBar 中相应位置(index) 的图像(当然,每个ListViewItem 都有自己的ProgressBar 分配)。

    关键是将相同的图像再次分配到ImageList 中的相同位置 - 这会导致重新绘制,没有它就无法工作。

    优点: 快速(不必编写自己的 UserControl)、便宜(对此进行了很多调查,但最终编写的代码并不多),并且可以工作

    缺点: 当有大量项目时,我注意到一些闪烁。此外,Mono 上还有一些令人耳目一新的问题。

    示例结果:

    带有示例应用程序的代码:https://github.com/bartoszkp/dotrl(BSD 许可证) - 特别是参见 BatchExperimentWindow 类:https://github.com/bartoszkp/dotrl/blob/master/Application/BatchExperimentWindow.cs

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2017-07-22
      • 2014-01-26
      • 2013-06-17
      相关资源
      最近更新 更多