分配事件之一时,如何通知我的控件? (解决了) [英] How to have my Control informed when one of its events is assigned? (Solved)

查看:79
本文介绍了分配事件之一时,如何通知我的控件? (解决了)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:
我设计了从TextBox继承的Control.
我已经实现了event,它可以很好地工作(能完成工作).

问题:
每当我从其他class(包含我的ControlForm)分配了event时,我都希望Control做一些事情(调用一种方法来检查某些东西并设置一些属性等). br/>
我相信这是可能的.

我尝试使用addremove关键字.
但是,这破坏了我的OnEventName方法中的代码.
看来用addremove语法声明的event既不能测试null也不能被调用...

那我该怎么办?
我帮助了很多人(我拥有金牌授权).也许我也可以得到别人的帮助.
谢谢.


一些代码:

Scenario:
I have designed a Control inheriting from TextBox.
I have implemented an event, which works well (does its job).

Problem:
I would like my Control to do something (invoke a method to check something and set some properties etc) every time this event is assigned from other class (the Form that contains my Control).

I am sure that this is possible.

I tried using add and remove keywords.
However, this broke my code in my OnEventName method.
It seems that an event declared with the add and remove syntax can neither be tested for null nor invoked...

So, what can I do?
I helped lots of people (I have gold authority). Maybe I can be helped by others too.
Thank you.


Some code:

public class MyTextBox : TextBox
{
    /* ... */

    public event MyEventHandler MyEvent;

    protected virtual void OnMyEvent(MyEventArgs e)
    {
        if (MyEvent != null)
            MyEvent(this, e);
    }

    /* ... */
}

public class MyForm : Form
{
    /* ... */

    private MyTextBox myTextBox;

    /* ... */

    public MyForm()
    {
        myTextBox = new MyTextBox();
        this.Controls.Add(myTextBox);
        myTextBox.MyEvent += SomeMethod; // Compatible arguments
        // And now, the Problem!
        // I want myTextBox to "feel" that something was assigned to its event and act accordingly.
    }

    /* ... */
}



我尝试的更改:



The change I tried:

public class MyTextBox : TextBox
{
    /* ... */

    public event MyEventHandler MyEvent
    {
        add { MyEvent += value; DoSomething(); }     // Here I grab the opportunity to react in some way...
        remove { MyEvent -= value; DoSomething(); }  // Same here.
    }

    protected virtual void OnMyEvent(MyEventArgs e)
    {
        if (MyEvent != null)   // Error: The event 'MyEvent' can only appear on the left hand side of += or -=
            MyEvent(this, e);  // The same error.
    }

    /* ... */
}

推荐答案

您尝试过类似的事情吗?

You tried something like this?

private EventHandler<EventArgs> onMyEvent;

public event EventHandler<EventArgs> MyEvent
{
add
{
Foo();
onMyEvent = (EventHandler<EventArgs>)Delegate.Combine(onMyEvent, value);
}
remove
{
Bar();
onMyEvent =(EventHandler<EventArgs>)Delegate.Remove(onMyEvent, value);
}
}


根据 ^ ],您可以测试是否存在null等.
According to these examples on MSDN[^], you are able to test for null etc.


这篇关于分配事件之一时,如何通知我的控件? (解决了)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆