gpt4 book ai didi

c# - 复选框(取消选中所有其他复选框

转载 作者:行者123 更新时间:2023-11-30 21:00:38 25 4
gpt4 key购买 nike

我创建了一个(到目前为止)仅包含复选框的 Windows 窗体。构造函数采用一个参数:string[] attributes。对于此 attributes 数组中的每个字符串,我创建了一个复选框。

例如:

string[] attributes = {
"Black",
"Red",
"Blue"
};
form1 = new MyForm(attributes);
form1.Show();

将像这样创建复选框:

[ ] Black
[ ] Red
[ ] Blue

这很好用。现在我的下一步是创建一个复选框“Check All”,它具有以下行为。我将使用 this 来引用我的“全部选中”复选框

时间:

  • 用户选中这个:选中所有其他复选框。
  • 用户取消选中:取消选中所有其他复选框。
  • 所有其他复选框都被手动选中:this 也被选中。
  • 所有复选框都被选中,其中任何一个都被取消选中:this 也被取消选中。

我设法执行了上述所有规则,但我遇到了一个问题,我不知道如何解决它:当所有复选框都被选中并且用户取消选中一个复选框时,这意味着我的 "Check所有”复选框 也将取消选中。现在我的“全部选中”复选框未选中,它会自动调用取消选中事件,然后取消选中所有复选框,就好像用户取消选中我的“全部选中”复选框一样.

那么有没有办法告诉我的复选框在另一个调用取消选中的复选框时不要运行 CheckedChanged

这是我的代码(都是手写的,所以没有使用 visual studio designer):

using System;
using System.Drawing;
using System.Windows.Forms;

class MyForm
{
public MyForm(string[] attributes)
{
SpawnControls(attributes);
}

private CheckBox[] m_attributes;
private CheckBox m_all;

private void SpawnControls(string[] attributes)
{
CheckBox dummy = new CheckBox();
int nAttr = attributes.Length;

m_attributes = new CheckBox[nAttr];
for (int i = 0; i < nAttr; i++)
{
m_attributes[i] = new CheckBox();
m_attributes[i].Text = attributes[i];
m_attributes[i].Location = new Point(5, dummy.Height * i);
m_attributes[i].CheckedChanged += attribute_CheckedChanged;
Controls.Add(m_attributes[i]);
}

m_all = new CheckBox();
m_all.Text = "Check All";
m_all.Location = new Point(5, m_attributes[nAttr - 1].Bottom);
m_all.CheckedChanged += all_CheckedChanged;
Controls.Add(m_all);
}

private void attribute_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
foreach (CheckBox cb in m_attributes)
{
if (cb.Checked == false)
{
return;
}
}
m_all.Checked = true;
}
else if (m_all.Checked)
{
m_all.Checked = false;
}
}

private void all_CheckedChanged(object sender, EventArgs e)
{
if (m_all.Checked)
{
foreach (CheckBox cb in m_attributes)
{
cb.Checked = true;
}
}
else
{
foreach (CheckBox cb in m_attributes)
{
cb.Checked = false;
}
}
}
}

最佳答案

您可以在事件处理程序的开头检查 All_Check 控件是否有焦点,如果没有焦点则退出事件。

private void all_CheckedChanged(object sender, EventArgs e)
{

if (!m_all.Focused)
return ;

if (m_all.Checked)
{
foreach (CheckBox cb in m_attributes)
{
cb.Checked = true;
}
}
else
{
foreach (CheckBox cb in m_attributes)
{
cb.Checked = false;
}
}
}

关于c# - 复选框(取消选中所有其他复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14797220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com