我在Windows Forms表单上有一个自绘的ListBox,绑定到数据源(BindingList)。我需要提供一种选择所有项目的选项(最多500000个),速度非常快。
这是我当前正在做的事情:
for (int i = 0; i < listBox.Items.Count; i++)
listBox.SetSelected(i, true);
这太慢了,无法接受。有人知道更好的解决方案吗?
BeginUpdate()
和EndUpdate()
方法。listBox.BeginUpdate();
for (int i = 0; i < listBox.Items.Count; i++)
listBox.SetSelected(i, true);
listBox.EndUpdate();
我找不到一种足够快速以至于可以被接受的方法。 我尝试了BeginUpdate/EndUpdate,虽然有所帮助,但在Intel Core i5笔记本电脑上仍需要4.3秒。 所以这很糟糕,但它能用 - 至少在IDE中是这样的。 ListBox被称为lbxItems,在表单上我有一个名为Select All的按钮。在该按钮的单击事件中,我有:
//save the current scroll position
int iTopIndex = lbxItems.TopIndex;
//select the [0] item (for my purposes this is the top item in the list)
lbxItems.SetSelected(0, true);
// put focus on the listbox
lbxItems.Focus();
//then send Shift/End (+ {END}) to SendKeys.SendWait
SendKeys.SendWait("+{END}");
// restore the view (scroll position)
lbxItems.TopIndex = iTopIndex;
结果:这可以在几毫秒内选择10,000个项目,就像我实际使用键盘一样。
https://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.selectall(v=vs.110).aspx
Listbox.SelectAll();
SelectAll
是否在内部禁用绘图)。 - RobSelectAll
方法。 - MyrtleSetSelected()
)。 - Frédéric Hamidi[DllImport("user32.dll", EntryPoint = "SendMessage")]
internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
// Select All
SendMessage(listBox.Handle, 0x185, (IntPtr)1, (IntPtr)(-1));
// Unselect All
SendMessage(listBox.Handle, 0x185, (IntPtr)0, (IntPtr)(-1));
listBox.SelectedItems = listBox.Items
这样的事情吗?对于SelectedIndexes
呢? - Rob