C#UserControl委托和事件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#UserControl委托和事件相关的知识,希望对你有一定的参考价值。

我在Windows窗体应用程序中的事件几乎没有问题。我无法访问Form1中的UserControl事件。

public partial class KomisControl : UserControl
{

    public KomisControl()
    {
        InitializeComponent();

    }
    private static KomisControl _instance;

    public static KomisControl Instance
    {
        get
        {
            if (_instance == null)
                _instance = new KomisControl();
            return _instance;
        }

    }
    public delegate void AddButtonEventHandler(object o, EventArgs e);

    public event AddButtonEventHandler AddButtonEv;

    protected virtual void OnAddButton()
    {
        AddButtonEv?.Invoke(this, EventArgs.Empty);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OnAddButton();

    }
}

Form1中:

Form1

答案

事件不是static所以只有类名才能访问它。您需要使用Instance变量,您需要在构造函数的范围内编写代码:

public Form1()
{
    //..all the other stuff.....
    KomisControl.Instance.AddButtonEv += ...

}

以上是关于C#UserControl委托和事件的主要内容,如果未能解决你的问题,请参考以下文章