1

我有一个CheckedListBox从下面以编程方式创建的控件...

Button btnSelectAll = new Button();
btnSelectAll.Text = "Select All";
btnSelectAll.Name = item.Id;
btnSelectAll.Tag = param.Id;
CheckedListBox chkListBox = new CheckedListBox();
chkListBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
//set the name and tag for downstream event handling since two-way bindings are not possible with control
chkListBox.Tag = param.Id;
chkListBox.Name = item.Id;
chkListBox.ItemCheck += new ItemCheckEventHandler(chkListBox_ItemCheck);
btnSelectAll.Click += new EventHandler(btnSelectAll_Click);

请注意,当我动态创建项目时,每当 chkListBox 上的 ItemCheck 被点击时,我还添加了一个事件处理程序。代码中的其他地方......我确实......

CheckedListBox tmpCheckedListBox = cntrl as CheckedListBox;
for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   tmpCheckedListBox.SetItemChecked(i, true);
}

当我执行上述操作时,它不会引发 ItemChecked 事件。如何引发此事件,就像用户单击该项目一样?

4

1 回答 1

2

一种方法是只调用分配给事件的相同方法并为发送者传递正确的控件,例如:

for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   tmpCheckedListBox.SetItemChecked(i, true);
   chkListBox_ItemCheck(tmpCheckedListBox.Items[i],null);
}

您通常可以通过传递EventArgs.Emptynull作为事件参数逃脱,但是如果您在事件处理程序中依赖它们,则需要构造正确的参数类并将其传递,例如:

for (int i = 0; i < tmpCheckedListBox.Items.Count; i++)
{
   var args = new ItemCheckEventArgs(i,true,tmpCheckedListBox.GetItemChecked(i));

   tmpCheckedListBox.SetItemChecked(i, true);
   chkListBox_ItemCheck(tmpCheckedListBox.Items[i],args);
}
于 2013-03-19T22:25:23.433 回答