分配事件之一时,如何通知我的控件? (解决了)

编程入门 行业动态 更新时间:2024-10-28 06:31:48
本文介绍了分配事件之一时,如何通知我的控件? (解决了)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

场景: 我设计了从TextBox继承的Control. 我已经实现了event,它可以很好地工作(能完成工作). 问题: 每当我从其他class(包含我的Control的Form)分配了event时,我都希望Control做一些事情(调用一种方法来检查某些东西并设置一些属性等). br/> 我相信这是可能的. 我尝试使用add和remove关键字. 但是,这破坏了我的OnEventName方法中的代码. 看来用add和remove语法声明的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); } }

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

更多推荐

分配事件之一时,如何通知我的控件? (解决了)

本文发布于:2023-07-22 10:41:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   分配   解决了   事件   通知

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!