创建此自定义控件并在客户端中测试它时,发送 ValueChanged() 事件时出现空异常错误:
自定义控件来源:
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();
}
}
}
然后以测试形式:
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 数据绑定规则。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)