简体   繁体   中英

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. 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:

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.

It would be more correct to use the ItemCheck event than the Click event (as the click may not have landed on a checkbox). 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. You can, however, defer the handling until events are processed using BeginInvoke , like this:

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 . 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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