简体   繁体   中英

Can't raise click event of a UserControl in C#

I have a dynamically added UserControl :

var listItem = new ListItem(/* arguments */);
listItem.Click += SetListItemColor;

panel.Controls.Add(listItem); // "panel" is FlowLayoutPanel

SetListItemColor:

private void SetListItemColor(object sender, EventArgs e)
{
    var listItem = (ListItem)sender;
    if (listItem.BackColor == Color.LightGray)
    {
        listItem.BackColor = Color.White;
    }
    else
    {
        listItem.BackColor = Color.LightGray;
    }
}

No change to the color happens when I click on the UserControl . However, for test purpose, I tried to change the event to EnabledChanged and change the Enabled property, the color does change:

var listItem = new ListItem(/* arguments */);
listItem.Enabled = false;
listItem.EnabledChanged += SetListItemColor;
listItem.Enabled = true;

panel.Controls.Add(listItem);

What's the problem?

EDIT: Since docking doesn't work in a FlowLayoutPanel, suggest setting the size of your control to the size of the panel. Set the ListItem margins to empty as below to get maximum fill. For debugging set the backcolor different to make sure you can see it:

        var listItem = new ListItem(/* arguments */);
        listItem.BackColor = Color.Yellow; // Debugging only
        listItem.Margin = Padding.Empty;
        listItem.Size = panel.Size;
        listItem.Click += SetListItemColor;

Note that if the control is resized you will need to resize your ListItem again.

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