【发布时间】:2011-08-24 15:25:40
【问题描述】:
我有 3 个列表框,我想在选择其中 1 个时取消选择其他列表框。我怎样才能做到这一点? 我尝试将focused属性设置为false,但c#不允许分配给focused属性。
【问题讨论】:
-
如果您要更改的是选择,为什么要更改焦点属性。这是 3.5 中的焦点 msdn.microsoft.com/en-us/library/…
我有 3 个列表框,我想在选择其中 1 个时取消选择其他列表框。我怎样才能做到这一点? 我尝试将focused属性设置为false,但c#不允许分配给focused属性。
【问题讨论】:
假设您有三个列表框,请执行以下操作。当特定列表框更改选择时,此代码将清除所有其他列表框的选择。您可以通过设置SelectedIndex = -1 来清除列表框选择。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
listBox2.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex > -1)
{
listBox1.SelectedIndex = -1;
listBox3.SelectedIndex = -1;
}
}
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox3.SelectedIndex > -1)
{
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
}
}
if (listBox#.SelectedIndex > -1) 是必要的,因为通过代码设置列表框的SelectedIndex 也会触发其SelectedIndexChanged 事件,否则会导致所有列表框在任何时候被选中时清除。
编辑:
或者,如果您的表单上只有这三个列表框,那么您可以将其合并为一种方法。将所有三个列表框链接到此事件方法:
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox thisListBox = sender as ListBox;
if (thisListBox == null || thisListBox.SelectedIndex == 0)
{
return;
}
foreach (ListBox loopListBox in this.Controls)
{
if (thisListBox != loopListBox)
{
loopListBox.SelectedIndex = -1;
}
}
}
【讨论】:
使用@Devin Burke 的答案,因此您不必担心表单中有其他控件:
using System.Linq;
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox thisListBox = sender as ListBox;
if (thisListBox == null || thisListBox.SelectedIndex == 0)
{
return;
}
foreach (ListBox loopListBox in this.Controls.OfType<ListBox>().ToList())
{
if (thisListBox != loopListBox)
{
loopListBox.SelectedIndex = -1;
}
}
}
【讨论】:
在我的 NET5/Winforms 小应用程序中,当前列表框的选定项不会保持蓝色/标记。
我发现解决方案是恢复焦点并设置索引。通过适当的类型检查改进通用解决方案,Nane 的回答,
private void lbDefect_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox thisListBox = sender as ListBox;
if (thisListBox == null || thisListBox.SelectedIndex == 0)
{
return;
}
var iSelected = thisListBox.SelectedIndex; // keep position..
foreach (ListBox loopListBox in this.Controls.OfType<ListBox>().ToList())
{
if (thisListBox != loopListBox)
{
loopListBox.SelectedIndex = -1;
}
}
// .. and this will show the selection for the current listbox
thisListBox.Focus();
thisListBox.SelectedIndex = iSelected;
}
【讨论】: