简体   繁体   English

如何将Winforms中按钮的Enabled属性绑定到CheckedListBox的CheckedItems.Count属性

[英]How to bind the Enabled property of a button in Winforms to the CheckedItems.Count property of a CheckedListBox

I have a CheckedListBox in a form. 我在表单中有一个CheckedListBox。 Each item represents an email message subject of a logged in user. 每个项目代表一个已登录用户的电子邮件主题。

形成

What I try to achieve is that when only one item is selected, both the Edit and Delete buttons should be enabled, otherwise disabled. 我试图实现的是,当仅选择一项时,应同时启用“编辑”和“删除”按钮,否则应禁用。

I have tried to use the following event handler after setting the CheckOnClick property to true, but it's not working: 将CheckOnClick属性设置为true后,我尝试使用以下事件处理程序,但是它不起作用:

private void clbEmailsSubjects_Click(object sender, EventArgs e)
{
    btnEdit.Enabled = btnDelete.Enabled = (clbEmailsSubjects.CheckedItems.Count == 1);
}

Any suggestions? 有什么建议么?

Edit: I had selected an item, but both buttons were still disabled. 编辑:我选择了一个项目,但两个按钮仍然被禁用。

在此处输入图片说明

Now, after selecting the second item they have become enabled: 现在,选择第二项后,它们已启用:

在此处输入图片说明

The effect seems to be contrary. 效果似乎是相反的。 I think the value of CheckedItems.Count might be updated after the event_handler is executed. 我认为在event_handler执行后,CheckedItems.Count的值可能会更新。

It would be more correct to use the ItemCheck event than the Click event (as the click may not have landed on a checkbox). 使用ItemCheck事件比Click事件会更正确(因为单击可能未落在复选框上)。 But either way, the event gets fired before the Checked property on the CheckBox gets changed, so you can't set the enabled states within either of those event handlers. 但无论哪种方式,都会在更改CheckBoxChecked属性之前触发该事件,因此您无法在这些事件处理程序中的任何一个中设置启用状态。 You can, however, defer the handling until events are processed using BeginInvoke , like this: 但是,您可以将处理推迟到使用BeginInvoke处理事件之前,如下所示:

private void clbEmailsSubjects_ItemCheck(object sender, ItemCheckEventArgs e)
{
    BeginInvoke((Action)(() =>
    {
        btnEdit.Enabled = btnDelete.Enabled =
            (clbEmailsSubjects.CheckedItems.Count == 1);
    }));
}

You need to register for the ItemCheck event on your CheckedListBox . 您需要在CheckedListBox上注册ItemCheck事件。 Then the following code will give you the desired result: 然后,以下代码将为您提供所需的结果:

    private void clbEmailsSubjects_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        btnEdit.Enabled = btnDelete.Enabled =
            (clbEmailsSubjects.CheckedItems.Count == 2 && e.NewValue == CheckState.Unchecked) ||
            (clbEmailsSubjects.CheckedItems.Count == 0 && e.NewValue == CheckState.Checked);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM