本文介绍了单击其子控件时如何返回用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个包含两个标签的用户控件.我在窗体上使用多个用户控件.在用户控件的单击事件中,我必须确定被单击的用户控件.当用户在标签区域之外单击时,我可以从发件人对象中投射用户控件,例如:

Hi,

I have a User Control which contains two Labels. I am using multiple user controls on a form. On click event of user control I have to determine the user control which was clicked. When user clicks outside the label area I can cast the user control from the sender object like:

UserControl1 obj=(UserControl1)sender;



但是,当用户单击标签时,将返回标签而不是UserControl.
即使单击标签,我也希望获得UserControl.



But when user clicks on labels, the label is returned instead of the UserControl.
I want to get UserControl even when the label is clicked.

推荐答案

public UserControl1()
        {
            InitializeComponent();
            MyLabel l = new MyLabel();
            l.Text = "Mylabel";
            l.BorderStyle = BorderStyle.FixedSingle;//to help you see its region
            l.Size = new Size(100, 50);
            l.Click += (sender, e) =>
            {
                //This is to test the success
                UserControl u = (UserControl)sender;
                MessageBox.Show(u.Name);
            };
            Controls.Add(l);
        }

        public class MyLabel : Label
        {
            public MyLabel()
            {
                base.Click += (sender, e) =>
                {
                    if(Click != null)
                        Click(this.Parent, e);
                };
            }
            public new event EventHandler Click;
        }
    }



希望能对您有所帮助,如果您仍然感到困惑,我很高兴向您解释更多.



Hope it helps, If you are still confused, I''m glad to explain more.


UserControl1 obj=(UserControl1)yourLable.parent;


简而言之, .Parent 是您要搜索的属性,
Control.parent返回其父控件

假设,
cont2放在con1内部
因此,Cont2.parent将返回cont1
祝您编码愉快!
:)


In short .Parent is a property you are searching for,
Control.parent returns it''s parent control

suppose,
cont2 is placed inside con1
so, Cont2.parent will return cont1
Happy Coding!
:)


这篇关于单击其子控件时如何返回用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:48