🧊讓 WinForms 的 DataGridView 在滾動時變得流暢:啟用 DoubleBuffered 技術
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1152
qX9,nM3(zY4+xH4%主題為「如何讓 WinForms DataGridView 在滾動時不再卡頓 —— 使用 DoubleBuffered 技術」。
WinForms 的 DataGridView
控制項雖然功能強大,但在面對大量資料、圖片或複雜格式時,滾動畫面經常會出現「卡頓」、「閃爍」的現象。這不僅影響使用者體驗,也讓介面顯得不夠專業。
幸好,透過啟用 DoubleBuffered
,我們可以大幅改善這個問題,讓畫面滾動更加順暢!
💡 為什麼 DataGridView 會卡頓?
原因主要在於:
-
每次滾動都會重繪畫面,而這個重繪是單層緩衝,容易出現閃爍與卡頓。
-
預設的
DataGridView
並沒有開啟DoubleBuffered
。 -
若你有用
CellFormatting
或RowPostPaint
來客製畫面,也會加劇問題。
✅ 解決方案:自訂一個 DoubleBufferedDataGridView 類別
因為 DoubleBuffered
屬性是 protected
的,不能直接從外部設定,所以我們需要用 反射(Reflection) 來開啟它。
📦 完整範例程式碼:
using System.Reflection;
using System.Windows.Forms;
public class DoubleBufferedDataGridView : DataGridView
{
public DoubleBufferedDataGridView()
{
// 使用反射設置 protected 的 DoubleBuffered 屬性
typeof(DataGridView)
.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic)
?.SetValue(this, true, null);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
}
🛠️ 如何使用?
方法一:程式動態建立
如果你是自己在程式碼中建立 DataGridView,可以這樣寫:
var dgv = new DoubleBufferedDataGridView();
dgv.Dock = DockStyle.Fill;
this.Controls.Add(dgv);
方法二:WinForms 設計器使用(Designer)
如果你是用設計器拖曳 DataGridView,那麼只需要改兩處 .Designer.cs
代碼即可:
① 改類別型別宣告:
// 原本:
private System.Windows.Forms.DataGridView dgvMain;
// 改成:
private DoubleBufferedDataGridView dgvMain;
② 改初始化的地方:
// 原本:
this.dgvMain = new System.Windows.Forms.DataGridView();
// 改成:
this.dgvMain = new DoubleBufferedDataGridView();
記得也要在 .Designer.cs
最上面加上 using
:
using YourNamespace; // 換成你自己的命名空間
🎯 效果驗證
使用這個自訂版本之後,DataGridView 滾動將變得非常順滑,幾乎不再閃爍與卡頓,特別適合以下情境:
-
顯示大量資料(數千筆以上)
-
每行帶有圖片或圖示
-
有自訂的格式化(如變色、加字型)
-
含多欄、多列 UI
📌 額外提示:還可以這樣優化
-
關閉不必要的功能,例如
RowHeadersVisible = false
、EnableHeadersVisualStyles = false
-
使用虛擬模式(VirtualMode)只載入可見資料
-
減少
CellFormatting
或RowPostPaint
中的邏輯運算
🧵 結語
啟用 DoubleBuffered
是提升 WinForms 表現的「小技巧大效果」之一,對於正在用 WinForms 開發系統介面的開發者來說,是絕對值得掌握的武器!
This article was last edited at