哪个 UserControl 调用 Event MouseEnter?

Which UserControl's calling Event MouseEnter?

我有一个 UserControl 的列表,我想知道哪个 UserControl 正在调用事件 MouseEnter。我在 TableLayoutPanel.

上添加了多个 UserControl
List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < dt.Rows.Count; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    form.Add(new MyUserControl());
}

for (int x = 0; x < form.Count; x++)
{    
    form[x].MouseEnter += new EventHandler(Form_MouseEnter);
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}

如何找出哪个 UserControl 激活了事件?

see in docmation

this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);

使用sender

private void panel1_MouseEnter(object sender, System.EventArgs e) 
{
    var userControl = sender as MyUserControl
}

最大的区别在于,如果您为新 MyUserControl 指定名称,因为默认名称是空字符串。您能否尝试将您的代码更改为这个,看看是否有帮助?

List<MyUserControl> form = new List<MyUserControl>();

for (int x = 0; x < 5; x++)
{
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200));
    if (x == 0)
        tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));

    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // Here are the changes
    MyUserControl myUserControl = new MyUserControl();
    myUserControl.Name = "MyUserControl_" + x.ToString("D2"); // Name it! (Default is "")                
    myUserControl.MouseEnter += MyUserControl_MouseEnter;     // Hook the MouseEnter here
    myUserControl.Codigo = 1000 + x;                          // Example to set Codigo     
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    form.Add(myUserControl); // NOTE! This is changed from 'new MyUserControl()'.
}

for (int x = 0; x < form.Count; x++)
{
    tableLayoutPanel1.Controls.Add(form[x], x, 0);
}

现在处理程序如下所示:

private void MyUserControl_MouseEnter(object sender, EventArgs e)
{
    MyUserControl myUserControl = (MyUserControl)sender;
    Debug.WriteLine(
        "MouseEnter Detected: " + myUserControl.Name + 
        " - Value of Codigo is: " + myUserControl.Codigo);
}

...其中(根据您对 Codigo 的评论)...

class MyUserControl : UserControl
{
    public int Codigo 
    { 
        set 
        { 
            test = value; 
        } 
        get 
        { 
            return test; 
        } 
    }
    int test = 0;
    // Of course there is more implementation of MyUserControl that follows...
}

我真的希望这能帮助您解决您遇到的问题。