2010-02-02 5 views
21

사용자 정의 컨트롤에 사용자 지정 이벤트를 제공하고 사용자 정의 컨트롤 내의 이벤트에서 이벤트를 호출하는 방법이 있습니까? (호출이 올바른 용어입니다 있는지 확실하지 않습니다)Winforms 사용자가 사용자 지정 이벤트를 제어합니다.

public partial class Sample: UserControl 
{ 
    public Sample() 
    { 
     InitializeComponent(); 
    } 


    private void TextBox_Validated(object sender, EventArgs e) 
    { 
     // invoke UserControl event here 
    } 
} 

그리고 MainForm :

public partial class Sample: UserControl 
{ 
    public event EventHandler TextboxValidated; 

    public Sample() 
    { 
     InitializeComponent(); 
    } 


    private void TextBox_Validated(object sender, EventArgs e) 
    { 
     // invoke UserControl event here 
     if (this.TextboxValidated != null) this.TextboxValidated(sender, e); 
    } 
} 

: 그리고

public partial class MainForm : Form 
{ 
    private Sample sampleUserControl = new Sample(); 

    public MainForm() 
    { 
     this.InitializeComponent(); 
     sampleUserControl.Click += new EventHandler(this.CustomEvent_Handler); 
    } 
    private void CustomEvent_Handler(object sender, EventArgs e) 
    { 
     // do stuff 
    } 
} 
+0

당신은 http://stackoverflow.com/questions/2151049/net-custom-event-organization-assistance –

답변

29

Steve가 게시 한 샘플에는 이벤트를 통과시킬 수있는 구문도 있습니다. 그것은 속성을 만드는 것과 비슷하다 :

class MyUserControl : UserControl 
{ 
    public event EventHandler TextBoxValidated 
    { 
     add { textBox1.Validated += value; } 
     remove { textBox1.Validated -= value; } 
    } 
} 
27

나는 당신이 원하는 것은이 같은 믿습니다 귀하의 양식에 :

public partial class MainForm : Form 
{ 
    private Sample sampleUserControl = new Sample(); 

    public MainForm() 
    { 
     this.InitializeComponent(); 
     sampleUserControl.TextboxValidated += new EventHandler(this.CustomEvent_Handler); 
    } 
    private void CustomEvent_Handler(object sender, EventArgs e) 
    { 
     // do stuff 
    } 
} 
+0

+1 도움이 도움이 질문에 대한 첫 번째 대답을 찾을 수 있습니다 대답 – Kevin

+0

굉장합니다. 곧바로 마술을하지 않았습니다. :) – Almo

관련 문제