繁体   English   中英

检测窗体上的哪个用户控件已被单击

[英]Detect which Usercontrol on a Form has been clicked

我这是什么情况? 我正在使用 C#。 我有一个表单,其中包含单个用户控件的多个实例。 用户控件具有三个按钮。 添加、关闭和选择。

我想要达到什么目标? 我想在单击其关闭按钮时获取用户控件实例的标签。

任何帮助,将不胜感激,

谢谢

在您的用户控件中,向按钮添加一个事件处理程序。 在 Eventhandler 中触发一个事件,您可以在 Form 中向该事件添加一个 eventhandler

编辑:像这样的东西 Edit2:改变它以满足海报要求

public delegate void UControlButtonCloseClickedHandler(UControl sender, EventArgs e);
public partial class UControl : UserControl
{
    public event UControlButtonCloseClickedHandler UControlButtonCloseClicked;

    public UControl()
    {
        InitializeComponent();

        btnAdd.Click += ButtonAdd_Click;
        btnSelect.Click += ButtonSelect_Click;
        btnClose.Click += ButtonClose_Click;
    }


    private void ButtonClose_Click(object sender, EventArgs e)
    {
        UControlButtonCloseClicked(this, new EventArgs());
    }
}

然后在您的表单中添加一个处理程序,如uControl.UControlButtonCloseClicked += Hanlder;

为什么不将每个按钮链接到同一个事件,然后获取控件的名称以确定它是否是关闭按钮(因为每个控件都必须具有唯一的名称,除非您动态地向表单添加控件,但即使如此,您应该分配一个名称)。 编辑:通过获取名称,我实际上是指比较触发事件的控件是否与您要执行关闭操作、打开操作等的控件相同。:)

        public Form1()
    {
        InitializeComponent();
        btnCloseButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton1.Click += new EventHandler(OnUserControlClick);
    }

    private static void OnUserControlClick(object sender, EventArgs e)
    {
        if (sender as UserControl == btnCloseButton)
        {
            this.Close();
        }
    }

暂无
暂无

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

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