1. 程式人生 > >C# 中DataGridView和ListView閃爍問題的解決方法

C# 中DataGridView和ListView閃爍問題的解決方法

最近在研究datagridview長列會閃爍的問題,困擾了我好幾天,原來是在datagridview重畫單元格時,會閃爍。在網上找到了一篇部落格,按照方法嘗試了一下,十分管用,驚喜╰(*°▽°*)╯

首先定義類,將此類放在datagridview或ListView所在的窗體類外面,然後程式碼如下,

 <summary>
/// 雙緩衝DataGridView,解決閃爍
/// 使用方法:在DataGridView所在窗體的InitializeComponent方法中更改控制元件型別例項化語句將
/// this.dataGridView1 = new System.Windows.Forms.DataGridView();   遮蔽掉,新增下面這句即可
/// this.dataGridView1 = new DoubleBufferListView();
/// </summary>
class DoubleBufferDataGridView : DataGridView
{
    public DoubleBufferDataGridView()
    {
        SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        //UpdateStatus.Continue;
        UpdateStyles();
    }
}
 
/// <summary>
/// 雙緩衝ListView ,解決閃爍
/// 使用方法是在ListView 所在窗體的InitializeComponent方法中,更改控制元件型別例項化語句將
/// this.listView1 = new System.Windows.Forms.ListView();    遮蔽掉, 新增下面語句即可
/// this.listView1 = new DoubleBufferListView();
/// </summary>
class DoubleBufferListView : ListView
{
    public DoubleBufferListView()
    {
        SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        UpdateStyles();
    }
}</span>
 

方法二
直接寫一個擴充套件方法,使用反射,直接上程式碼,將此類定義給DataGirdView或ListView所在的窗體類外面即可

public static class DoubleBufferDataGridView
{
    /// <summary>
    /// 雙緩衝,解決閃爍問題
    /// </summary>
    /// <param name="dgv"></param>
    /// <param name="flag"></param>
    public static void DoubleBufferedDataGirdView(this DataGridView dgv, bool flag)
    {
        Type dgvType = dgv.GetType();
        PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(dgv, flag, null);
    }
}
 
public static class DoubleBufferListView
{
    /// <summary>
    /// 雙緩衝,解決閃爍問題
    /// </summary>
    /// <param name="lv"></param>
    /// <param name="flag"></param>
    public static void DoubleBufferedListView(this  ListView lv, bool flag)
    {
        Type lvType = lv.GetType();
        PropertyInfo pi = lvType.GetProperty("DoubleBuffered",
            BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(lv, flag, null);
    }
 
}

兩個方法都嘗試了一下,相比較第二個方式對於我來說效果更好。