简体   繁体   English

无法在C#中引发UserControl的点击事件

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

I have a dynamically added UserControl : 我有一个动态添加的UserControl

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

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

SetListItemColor: 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 . 当我单击UserControl时,颜色没有改变。 However, for test purpose, I tried to change the event to EnabledChanged and change the Enabled property, the color does change: 但是,出于测试目的,我试图将事件更改为EnabledChanged并更改Enabled属性,但颜色确实发生了变化:

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. 编辑:由于停靠在FlowLayoutPanel中不起作用,建议将控件的大小设置为面板的大小。 Set the ListItem margins to empty as below to get maximum fill. 将ListItem页边距设置为空,如下所示,以获取最大填充量。 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. 请注意,如果调整控件的大小,则需要再次调整ListItem的大小。

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

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