Winforms użytkownik kontroluje zdarzenia niestandardowe

Czy istnieje sposób na nadanie kontrolce użytkownika niestandardowych zdarzeń i wywołanie zdarzenia na zdarzeniu wewnątrz kontrolki użytkownika. (Nie jestem pewien, czy invoke jest poprawnym terminem)

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


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

I Główne:

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
    }
}
Author: GEOCHET, 2010-02-02

2 answers

Oprócz przykładu, który opublikował Steve, dostępna jest również składnia, która może po prostu przekazać Zdarzenie. Jest to podobne do tworzenia właściwości:

class MyUserControl : UserControl
{
   public event EventHandler TextBoxValidated
   {
      add { textBox1.Validated += value; }
      remove { textBox1.Validated -= value; }
   }
}
 32
Author: Ed S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-02 22:18:35

Wierzę, że chcesz czegoś takiego:

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

A następnie na formularzu:

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
    }
}
 28
Author: Steve Danner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-09 20:53:22