如何从外部创建控件和事件 C# 窗体



如何从外部创建控件和事件 C# 形式

namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}

class  Methods 
{
//need to create method to Form 1 From herer
}
class EventHandler
{
//need to create EventHandler to Form 1 From herer
}
class CreateControl
{
//dynamically Create controls for Form1 From this class
}    
}

像这样的东西,如果我理解正确的话:

Form myForm = ...
// Let's create a button on myForm
Button myButton = new Button() {
Text = "My Button",           //TODO: specify all the properties required here 
Size = new Size(75, 25),
Location = new Point(30, 40),
Parent = myForm,              // Place on myForm instance
};
// We can implement an event with a help of lambda
myButton.Click += (s, ea) => { 
//TODO: put relevant code here
};

虽然我没有看到这样做有任何好处,但这将是您想要的:

namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Methods.Init(this);
}
}

class  Methods 
{
//need to create method to Form 1 From herer
public static void Init(Form frm)
{
frm.Controls.Add((new CreateControl()).CreateButton("Test"));
}
}
class EventHandlerWrapper
{
//need to create EventHandler to Form 1 From herer
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show("TEST");
}
}
class CreateControl
{
public Button CreateButton(string text)
{
EventHandlerWrapper e = new EventHandlerWrapper();
Button btn = new Button();
btn.Text = text;
btn.Click += e.button_Click;
}
}    
}

最新更新