gpt4 book ai didi

c# - 如何在控件实例化后立即发送自定义事件消息?

转载 作者:行者123 更新时间:2023-12-02 14:37:21 29 4
gpt4 key购买 nike

创建此自定义控件并在客户端中测试它时,发送 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:有一个接口(interface) INotifyPropertyChanged,您应该使用它来遵守标准 .NET 数据绑定(bind)规则。

关于c# - 如何在控件实例化后立即发送自定义事件消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379627/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com