[英]How to detach event handlers from HtmlElement objects? c#
first of all, I'm new to this forum and relatively new to programming. 首先,我是这个论坛的新手,对编程来说还是比较新的。 My problem is that I can't detach event handlers attached previously.
我的问题是我无法分离以前附加的事件处理程序。 At least, DetachEventHandler in the following code doesn't do it:
至少,以下代码中的DetachEventHandler无法做到:
private void addHandlersToElement(HtmlElement thiselement)
{
thiselement.DetachEventHandler("onclick", delegate { myClickHandler(thiselement, EventArgs.Empty); });
thiselement.AttachEventHandler("onclick", delegate { myClickHandler(thiselement, EventArgs.Empty); });
}
It obviously doesn't work because the code in the event handler executes as many times as I called addHandlersToElements , that is, attach works but detach doesn't. 显然,这是行不通的,因为事件处理程序中的代码执行的次数与我称为addHandlersToElements的执行次数相同,也就是说,附加操作有效,而分离操作却无效。
The truth is that I don't know very much about delegates, just that they are wrappers for methods to make it possible to pass them as parameters. 事实是,我对委托人不是很了解,只是他们是方法的包装,使它们可以作为参数传递。 This delegate{} block I stole from some post, because this seemed the only solution to work for passing thiselement as the sender object (which I'm referring to in my actual handler method).
我从某篇文章中窃取了这个proxy {}块,因为这似乎是将thiselement作为sender对象传递的唯一解决方案(我在我的实际处理程序方法中指的是)。 Using
运用
new EventHandler(myMouseoverEventHandler)
for parameter actually works, but then, AFAIK, I cannot pass the sender. for参数实际上有效,但是后来AFAIK,我无法通过发送者。
Any help would be appreciated. 任何帮助,将不胜感激。
I think it will solve the problem if you assign the delegate to a reference, like this: 我认为如果将委托分配给引用,它将解决此问题,如下所示:
var del = delegate { myClickHandler(thiselement, EventArgs.Empty); };
and then attach and detach the same delegate object instead of attaching one delegate and detaching another: 然后附加和分离相同的委托对象,而不是附加一个委托并分离另一个委托:
thiselement.AttachEventHandler("onclick", del);
thiselement.DetachEventHandler("onclick", del);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.