Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何设置自定义控件按钮';在把它添加到某个表单之后,它的工作是什么?_C#_Winforms_Button_User Controls - Fatal编程技术网

C# 如何设置自定义控件按钮';在把它添加到某个表单之后,它的工作是什么?

C# 如何设置自定义控件按钮';在把它添加到某个表单之后,它的工作是什么?,c#,winforms,button,user-controls,C#,Winforms,Button,User Controls,我正在制作一个名为[File_Manager]的用户控件,我想知道是否可以在这个自定义控件中添加一个按钮,以便在将这个自定义控件添加到另一个窗体之后设置它的工作。。差不多 File_Manager fManager = new File_Manager(); fManager.SetFreeButtonJob( MessageBox.Show("Hello") ); // something like this. 然后每当用户按下该按钮。。消息框出现了 所以。。有可能吗 提前谢谢。当然可以。

我正在制作一个名为[File_Manager]的用户控件,我想知道是否可以在这个自定义控件中添加一个按钮,以便在将这个自定义控件添加到另一个窗体之后设置它的工作。。差不多

File_Manager fManager = new File_Manager();

fManager.SetFreeButtonJob( MessageBox.Show("Hello") ); // something like this.
然后每当用户按下该按钮。。消息框出现了

所以。。有可能吗


提前谢谢。

当然可以。只需将按钮单击处理程序附加到传入的操作

fManager.SetFreeButtonJob(() => MessageBox.Show("Hello"));
private void SetFreeButtonJob(Action action)
{
    button1.Click += (s,e) => action();
}
只需注意,传入操作会破坏用户控件的封装。您可能应该执行类似于
SetFreeButtonJob(Jobs.SayHello)的操作并将操作知识放入控件中。

用户控件创建一个控件,并在单击
按钮时启动它。然后,您可以在
表单
中将事件处理程序附加到自定义事件。或者,您可以在单击
按钮时引发
用户控件的
单击
事件

public delegate void CustomClickEventHandler(object sender, EventArgs e);

public partial class buttonTest : UserControl
{
    public event CustomClickEventHandler CustomClick;
    public buttonTest()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        CustomClick(sender, e);
    }
}
在您的
表格中

public Form1()
{
    InitializeComponent();

    buttonTest1.CustomClick +=new CustomClickEventHandler(userControl1_ButtonClick);

}

private void  userControl1_ButtonClick(object sender, EventArgs e)
{
    MessageBox.Show("Hello"); 
}
或者作为我的第二个选择

private void button2_Click(object sender, EventArgs e)
{
    OnClick(e);
}
然后在
表单中
订阅UserControl的单击事件

buttonTest1.Click +=new EventHandler(buttonTest1_Click);


private void buttonTest1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello Again"); 
}

为什么不使用Click事件?@ionden如何使用表单中的Click事件..如果自定义控件拥有该按钮。。