2017-07-12 7 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

「ここからフォーム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; 
     } 
    }  
} 
関連する問題