gpt4 book ai didi

.net - 如何避免成千上万的不必要的ListView.SelectedIndexChanged事件?

转载 作者:行者123 更新时间:2023-12-03 14:51:02 28 4
gpt4 key购买 nike

如果用户选择.NET 2.0 ListView中的所有项目,则ListView将为每个项目触发SelectedIndexChanged事件,而不是触发事件以指示选择已更改。

如果用户随后单击以仅选择列表中的一个项目,则ListView将为每个未选中的项目触发一个SelectedIndexChanged事件,然后为单个新选择的项目触发一个SelectedIndexChanged事件,而不是触发一个事件来指示选择已更改。

如果您在SelectedIndexChanged事件处理程序中有代码,则当列表中开始有成百上千个项目时,程序将变得无响应。

我已经考虑过停留计时器等。

但是,没有人有一个好的解决方案来避免成千上万个不必要的ListView.SelectedIndexChange事件,而实际上只有一个事件可以做到吗?

最佳答案

伊恩的好解决方案。我将其放入可重用的类中,确保正确处置了计时器。我还缩短了获取响应速度更快的应用程序的时间间隔。此控件还具有双缓冲区以减少闪烁。

  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:
/// http://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());
}
}


让我知道是否可以改善。

关于.net - 如何避免成千上万的不必要的ListView.SelectedIndexChanged事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/86793/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com