【发布时间】:2011-11-19 22:41:34
【问题描述】:
在 WinForms 中,我偶尔会在列表框上运行一个循环来选择项目。
在此期间,我不希望用户使用鼠标或键选择该列表框中的项目。
我查看了 MyListbox.enabled=false 但它使所有项目变灰。不想这样。
如何防止选择列表框中的项目?
【问题讨论】:
在 WinForms 中,我偶尔会在列表框上运行一个循环来选择项目。
在此期间,我不希望用户使用鼠标或键选择该列表框中的项目。
我查看了 MyListbox.enabled=false 但它使所有项目变灰。不想这样。
如何防止选择列表框中的项目?
【问题讨论】:
创建一个从 Listbox 移除焦点的事件处理程序,并将该处理程序订阅到 Listbox 的 GotFocus 事件。这样,用户将永远无法在列表框中选择任何内容。以下代码行使用内联匿名方法完成此操作:
txtBox.GotFocus += (object anonSender, EventArgs anonE) => { txtBox.Parent.Focus(); };
*编辑:代码说明
【讨论】:
我也想要一个只读的列表框,终于在http://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html找到了这个:
public class ReadOnlyListBox : ListBox
{
private bool _readOnly = false;
public bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
protected override void DefWndProc(ref Message m)
{
// If ReadOnly is set to true, then block any messages
// to the selection area from the mouse or keyboard.
// Let all other messages pass through to the
// Windows default implementation of DefWndProc.
if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E)
&& (m.Msg <= 0x0100 || m.Msg >= 0x0109)
&& m.Msg != 0x2111
&& m.Msg != 0x87))
{
base.DefWndProc(ref m);
}
}
}
【讨论】:
如果您将 ListBox 子类化并覆盖 OnMouseClick 方法,您可能会有一些运气:
public class CustomListBox : ListBox
{
public bool SelectionDisabled = false;
protected override void OnMouseClick(MouseEventArgs e)
{
if (SelectionDisabled)
{
// do nothing.
}
else
{
//enable normal behavior
base.OnMouseClick(e);
}
}
}
当然,您可能希望做更好的信息隐藏或类设计,但这是基本功能。您可能还需要覆盖其他方法。
【讨论】:
将Listbox.SelectionMode 属性切换为SelectionMode.None
编辑 正如我所见,设置为SelectionMode.None 会取消选择所有先前选择的项目,如果在列表框上调用SetSelected,则会引发异常。
我认为所需的行为是不可能的(不想用Enabled=false 将项目变灰)。
【讨论】: