我是編程界的新手,無法理解如何在這裏使用這段代碼:How to avoid thousands of needless ListView.SelectedIndexChanged events作者:Robert Jeppesen。如何在C#中使用可重用類來改進窗體工具?
public class DoublebufferedListView : System.Windows.Forms.ListView
{
private Timer m_changeDelayTimer = null;
public DoublebufferedListView()
: base()
{
// Set common properties for our listviews
if (!SystemInformation.TerminalServerSession)
{
DoubleBuffered = true;
SetStyle(ControlStyles.ResizeRedraw, true);
}
}
/// <summary>
/// Make sure to properly dispose of the timer
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing && m_changeDelayTimer != null)
{
m_changeDelayTimer.Tick -= ChangeDelayTimerTick;
m_changeDelayTimer.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Hack to avoid lots of unnecessary change events by marshaling with a timer:
/// https://stackoverflow.com/questions/86793/how-to-avoid-thousands-of-needless-listview-selectedindexchanged-events
/// </summary>
/// <param name="e"></param>
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (m_changeDelayTimer == null)
{
m_changeDelayTimer = new Timer();
m_changeDelayTimer.Tick += ChangeDelayTimerTick;
m_changeDelayTimer.Interval = 40;
}
// When a new SelectedIndexChanged event arrives, disable, then enable the
// timer, effectively resetting it, so that after the last one in a batch
// arrives, there is at least 40 ms before we react, plenty of time
// to wait any other selection events in the same batch.
m_changeDelayTimer.Enabled = false;
m_changeDelayTimer.Enabled = true;
}
private void ChangeDelayTimerTick(object sender, EventArgs e)
{
m_changeDelayTimer.Enabled = false;
base.OnSelectedIndexChanged(new EventArgs());
}
}
所以它是一個可重用的類,我想添加到我已有的ListView中。我目前使用Ian Boyd提供的代碼在同一網址上進行管理,並將此代碼添加到所有ListView中。問題是我目前正在使用的ERP程序中已經有很多ListView,並且新的程序一直在運行。看起來像是浪費時間重寫相同的代碼。
Timer changeDelayTimer = null;
private void lvResults_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.changeDelayTimer == null)
{
this.changeDelayTimer = new Timer();
this.changeDelayTimer.Tick += ChangeDelayTimerTick;
this.changeDelayTimer.Interval = 200; //200ms is what Explorer uses
}
this.changeDelayTimer.Enabled = false;
this.changeDelayTimer.Enabled = true;
}
private void ChangeDelayTimerTick(object sender, EventArgs e)
{
this.changeDelayTimer.Enabled = false;
this.changeDelayTimer.Dispose();
this.changeDelayTimer = null;
//Add original SelectedIndexChanged event handler code here
//todo
}
我試圖從谷歌搜索這個主題的答案,但我找不到我正在使用的關鍵字的正確文章。希望這裏的某個人能夠指導我如何將這些被認爲是「組件」的'類'與windows窗體工具一起使用的正確方向。
您的課程必須已經在您的項目的工具箱中(至少在建立後)。確保你的團隊在需要新的ListView時使用你的控件。然後將所有存在的ListView控件更改爲您的控件。因爲它是從ListView派生的,所以可以通過用「Find-Replace」代替ListView聲明和構造函數執行代碼來實現 – Fabio
這是一個有用的方法Fabio,thx。 –