我想要回答这个问题 [英] i want ans for this question

查看:67
本文介绍了我想要回答这个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从C#中的不同按钮调用不同的用户控件。



如何从C#

how to call different user controls from different buttons in C#.
or
how to call multiple user controls from multiple buttons in C#

推荐答案

只需添加对用户控件的引用,然后调用该控件的方法。



你应该能够拖放用户控件在窗体上,然后通过属性访问它们。
Just add a reference to the user control and then call methods of that control.

You should be able to drag and drop user controls on the form and then access them via properties as well.


HI,



你需要创建一个事件处理程序对于usercontrol的按钮事件,并从实际按钮的click事件中触发它。





You need to create an event handler for the button-event of the usercontrol and fire it from the click event of the actual button.

class MyControl : UserControl
{
    public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
    public event ButtonClickedEventHandler OnUserControlButtonClicked;
}

Now you need to listen to the event of the actual button:

class MyControl : UserControl
{
    public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
    public event ButtonClickedEventHandler OnUserControlButtonClicked;

    public MyControl()
    {
        _myButton.Clicked += new EventHandler(OnButtonClicked);
    }

    private void OnButtonClicked(object sender, EventArgs e)
    {
        // Delegate the event to the caller
        if (OnUserControlButtonClicked != null)
            OnUserControlButtonClicked(this, e);
    }
}





从主表单(所有者),您现在可以收听此活动:



From the main form (owner) you can now listen to the event:

public DemoForm : Form
{
    public DemoForm()
    {
        _myUserControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
    }

    private void OnUCButtonClicked(object sender, EventArgs e)
    {
        // Handle event from here
        MessageBox.Show("Hello");
    }
}





谢谢



Thanks


这篇关于我想要回答这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆