Meh*_*ANI 65
事实是,它ListBox.Items
是一个普通的对象集合并返回普通的无类型对象,这些对象不能被多选(默认情况下).
如果您想多选所有项目,那么这将有效:
for (int i = 0; i < myListBox.Items.Count;i++)
{
myListBox.SetSelected(i, true);
}
Run Code Online (Sandbox Code Playgroud)
我已经看到了许多(类似的)答案,这些答案在逻辑上都是一样的,我很困惑为什么他们都不适合我.关键是将列表框设置SelectionMode
为SelectionMode.MultiSimple
.它不起作用SelectionMode.MultiExtended
.考虑到在列表框中选择多个项目,您将选择模式设置为多种模式,并且大多数人都选择传统MultiExtended
风格,这个答案应该有很多帮助.而且你不是foreach
,但是for
.
你应该这样做:
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
lb.SetSelected(i, true);
lb.SelectionMode = //back to what you want
Run Code Online (Sandbox Code Playgroud)
要么
lb.SelectionMode = SelectionMode.MultiSimple;
for (int i = 0; i < lb.Items.Count; i++)
lb.SelectedIndices.Add(i);
lb.SelectionMode = //back to what you want
Run Code Online (Sandbox Code Playgroud)
据我所知,使用任何.NET方法选择大量项目远比进行直接PInvoke调用慢,将LB_SETSEL消息(0x185)传递给控件,并带有一个标志,指示是否要选择(1)或取消选择(0)以及魔术值(-1),表示更改应适用于所有项目.
[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));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57700 次 |
最近记录: |