winForms 中的事件处理程序逻辑,用于一次选中一个复选框


    namespace explorer
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                DirectoryInfo di = new DirectoryInfo("c:\test");
                FileSystemInfo[] files = di.GetFileSystemInfos();
                checkedListBox1.Items.AddRange(files);
            }
            private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix)
                if (ix != e.Index) checkedListBox1.SetItemChecked(ix, false); 
            }
            //removed irrelevant parts of the code
        }
    }

我忘记了如何为复选框构建事件处理程序。我需要一个选择。我有多个文件,但我只需要一个通过复选框选择的文件。

您需要关闭事件处理程序或使用变量作为标志以避免堆栈溢出,因为您要取消选中 ItemCheck 事件中的项目:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
  for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
    if (ix != e.Index) {
      checkedListBox1.SetItemChecked(ix, false);
    }
  }
  checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}

使用变量的示例:

bool checkFlag = false;
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  if (!checkFlag) {
    checkFlag = true;
    for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
      if (ix != e.Index) {
        checkedListBox1.SetItemChecked(ix, false);
      }
    }
    checkFlag = false;
  }
}

您可以创建List<FileSystemInfo>集合,并在选中时将每个选中的文件添加到其中,并在取消选中时将其删除。处理程序本身已经创建,如我所见(checkedListBox1_ItemCheck)。也许你应该考虑把问题写得更清楚,因为也许我理解你不完全正确?

最新更新