我有一个文本框,我想将所选项目的数量限制为 MaxSelection。期望的行为是,一旦选择了 MaxSelection 项,任何进一步的选择都将被忽略。 (因此这个问题与“limit selections in a listbox in vb.net”不同)。
我有一个用于尝试完成此操作的列表框的 SelectedIndexChanged 事件的事件处理程序。如果用户按住 Ctrl 键并单击选择第 (MaxSelection+1) 个项目,则该选择将恢复为之前的选择。
问题是当用户选择一个项目,然后按住 Shift 键并单击列表下方的某个项目(该项目是列表下方的 MaxSelection+1 个项目)时。在这种情况下,会引发多个 SelectedIndexChanged 事件:一个用于按住 Shift 键单击,选择按住 Shift 键单击的项目,另一个用于选择原始选择和按住 Shift 键单击的选择之间的所有项目。第一个事件允许用户选择按住 Shift 键单击的项目(这在技术上是正确的),然后第二个事件将选择恢复为第一个事件之后的选择(这将是最初选择的项目,并且 Shift - 单击的项目)。期望的是代码将选择恢复为第一个事件之前的选择(这只是最初选择的项目)。
有什么方法可以在按住 Shift 键并单击之前保留选择吗?
谢谢, 罗布
这是 SelectedIndexChanged 事件处理程序:
void ChildSelectionChanged(object sender, EventArgs e)
{
ListBox listBox = sender as ListBox;
//If the number of selected items is greater than the number the user is allowed to select
if ((this.MaxSelection != null) && (listBox.SelectedItems.Count > this.MaxSelection))
{
//Prevent this method from running while reverting the selection
listBox.SelectedIndexChanged -= ChildSelectionChanged;
//Revert the selection to the previous selection
try
{
for (int index = 0; index < listBox.Items.Count; index++)
{
if (listBox.SelectedIndices.Contains(index) && !this.previousSelection.Contains(index))
{
listBox.SetSelected(index, false);
}
}
}
finally
{
//Re-enable this method as an event handler for the selection change event
listBox.SelectedIndexChanged += ChildSelectionChanged;
}
}
else
{
//Store the current selection
this.previousSelection.Clear();
foreach (int selectedIndex in listBox.SelectedIndices)
{
this.previousSelection.Add(selectedIndex);
}
//Let any interested code know the selection has changed.
//(We do not do this in the case where the selection would put
//the selected count above max since we revert the selection;
//there is no net effect in that case.)
RaiseSelectionChangedEvent();
}
}
最佳答案
某些第 3 方组件具有可取消的事件,例如 BeforeSelectedIndexChanged。
但是当使用MS默认组件时,我认为你的方法基本上是你所需要的。您还可以将选择存储在其他事件(例如 MouseDown 或 KeyDown)中,这些事件已知会在更改之前触发。
关于c# - 如果在列表框中选择了 X 个以上的项目,则恢复到之前的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/749057/