【问题标题】:Winforms user controls custom eventsWinforms 用户控件自定义事件
【发布时间】:2011-01-12 09:11:49
【问题描述】:

有没有办法给用户控件自定义事件,并在用户控件内的事件上调用事件。 (我不确定调用是否正确)

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


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

主窗体:

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

【问题讨论】:

标签: c# .net winforms user-controls event-handling


【解决方案1】:

除了史蒂夫发布的示例之外,还有一些可用的语法可以简单地传递事件。类似于创建属性:

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

【讨论】:

    【解决方案2】:

    我相信你想要的是这样的:

    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.TextboxValidated += new EventHandler(this.CustomEvent_Handler);
        }
        private void CustomEvent_Handler(object sender, EventArgs e)
        {
            // do stuff
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 2010-11-08
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多