2017-07-12 20 views
-3

如何從輸出端創建控件事件的形式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 
    }  
} 
+2

你爲什麼要這麼做?雖然這是完全可能的,但我沒有看到它的任何價值 –

+0

你是什麼意思的「從這裏創建方法Form 1」?你究竟在做什麼,爲什麼? – David

+0

創建'Form1'的具體實現,然後使用反射,添加方法和處理程序。您將需要一個工廠類來生成'Form1'的具體實現的實例,然後使用反射來添加方法和處理程序。考慮到你的問題的稀疏性,我建議你閱讀這個 - https://stackoverflow.com/help/how-to-ask – Alex

回答

2

這樣的事情,如果我理解你的權利:

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 
    }; 
0

雖然我沒有看到這樣做的任何利益,這將是你想要什麼:

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; 
     } 
    }  
} 
相關問題