C#使用ListView更新数据出现闪烁解决办法

2023-03-13,,

C#使用ListView更新数据出现闪烁解决办法

在使用vs自动控件ListView控件时候,更新里面的部分代码时候出现闪烁的情况

如图:

解决以后:

解决办法使用双缓冲:添加新类继承ListView 对其重写

 public class DoubleBufferListView : ListView
{
public DoubleBufferListView()
{
SetStyle(ControlStyles.DoubleBuffer |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint, true);
UpdateStyles();
}
}

新建一个DemoTest测试

1.添加一个DoubleBufferListView的实例

       DoubleBufferListView doubleBufferListView1= new DoubleBufferListView();
//
// doubleBufferListView1
//
this.doubleBufferListView1.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)()));
this.doubleBufferListView1.FullRowSelect = true;
this.doubleBufferListView1.HideSelection = false;
this.doubleBufferListView1.Location = new System.Drawing.Point(, );
this.doubleBufferListView1.Name = "doubleBufferListView1";
this.doubleBufferListView1.Size = new System.Drawing.Size(, );
this.doubleBufferListView1.TabIndex = ;
this.doubleBufferListView1.UseCompatibleStateImageBehavior = false;
this.doubleBufferListView1.View = System.Windows.Forms.View.Details;

2.将其添加到form窗体里面

 this.Controls.Add(this.doubleBufferListView1);

3.给添加列

        doubleBufferListView1.Clear();
doubleBufferListView1.Columns.Add("Action", , System.Windows.Forms.HorizontalAlignment.Left);
doubleBufferListView1.Columns.Add("value", , System.Windows.Forms.HorizontalAlignment.Right);
doubleBufferListView1.Columns.Add("Action", , System.Windows.Forms.HorizontalAlignment.Left);
doubleBufferListView1.Columns.Add("value", , System.Windows.Forms.HorizontalAlignment.Left);

4.随便添加点内容

         string[] listViewData = new string[];
listViewData[] = "Action";
listViewData[] = "";
listViewData[] = "Action";
listViewData[] = "";
ListViewItem lvItem = new ListViewItem(listViewData, );
doubleBufferView1.Items.Add(lvItem);

5.点击按钮开始运行

 private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(PlayGame);
if (state == false)
{
state = true;
button1.Text = "停止";
th.IsBackground = true;
th.Name = "新线程";
th.Start();
}
else
{
state = false;
button1.Text = "开始"; }
}
private void PlayGame()
{
Random r = new Random();
while (state)
{
string temp = r.Next(, ).ToString();
label1.Text = temp;
this.doubleBufferListView1.Items[].SubItems[].Text = temp;
}
}

6.运行对比图:

左侧是解决闪屏后,右侧是自带的ListView效果

C#使用ListView更新数据出现闪烁解决办法的相关教程结束。

《C#使用ListView更新数据出现闪烁解决办法.doc》

下载本文的Word格式文档,以方便收藏与打印。