如何在控件实例化后发送自定义事件消息?

我在创建此自定义控件并在客户端中测试时发送ValueChanged()事件时出现nullexception错误:

自定义控件的来源:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace customevent { [DefaultEvent("ValueChanged")] public partial class UserControl1 : UserControl { private int m_value; public delegate void ValueChangedHandler(); [Category("Action")] [Description("Value changed.")] public event ValueChangedHandler ValueChanged; public int Value { get { return m_value; } set { m_value = value; ValueChanged(); } } public UserControl1() { InitializeComponent(); } public UserControl1(int iValue) { this.Value = iValue; InitializeComponent(); } } } 

然后以测试forms:

  private void Form1_Load(object sender, EventArgs e) { userControl11.Value = 100; } private void userControl11_ValueChanged() { MessageBox.Show(userControl11.Value.ToString()); } 

或者代替form_load,在构造函数中执行此操作:

  private void InitializeComponent() { this.userControl11 = new customevent.UserControl1(100); 

您应该将事件处理声明为:

 public event EventHandler ValueChanged; protected virtual void OnValueChanged(object sender, EventArgs e) { if (ValueChanged != null) { ValueChanged(sender, e); } } public int Value { get { return m_value; } set { if (m_value == value) return; m_value = value; OnValueChanged(this, EventArgs.Empty); } } 

PS:有一个接口INotifyPropertyChanged,你应该使用它来代替标准的.NET数据绑定规则。

你没有检查空值:

  public int Value { get { return m_value; } set { m_value = value; if(ValueChanged != null) { ValueChanged(); } } } 

此外,您还没有在表格中加入此活动:

 private void Form1_Load(object sender, EventArgs e) { userControl1.ValueChanged += userControl11_ValueChanged; userControl11.Value = 100; } private void userControl11_ValueChanged() { MessageBox.Show(userControl11.Value.ToString()); } 

西蒙几乎到了你那里:

 protected virtual void OnValueChanged(object sender, EventArgs e) { var tmp = ValueChanged; if (tmp != null) { tmp(sender, e); // With the tmp, we won't explode if a subscriber changes the collection of delegates underneath us. } }