在 C# 中引发外部对象事件
如果 actions
是一个面板,我是否能够引发其父面板的 Click
事件? 我目前有此代码,但 Click
事件不是方法,因此此代码无效。
有谁知道我怎样才能实现这一目标?
actions.Click += delegate(object Sender, EventArgs e)
{
((Panel)Sender).Parent.Click();
}
If actions
is a Panel, am I able to raise the Click
event of it's parent?
I have this code at the moment, but the Click
event isn't a method, so this code is invalid.
Does anyone know how I can achieve this?
actions.Click += delegate(object Sender, EventArgs e)
{
((Panel)Sender).Parent.Click();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
无法直接从另一个
类
引发 C#事件
(即使它是public
)。 您可以提供一个代表您引发事件
的方法(具有足够的访问修饰符),并在另一个类
中调用该方法。顺便说一句,这可以通过反射实现,但我认为这是一个肮脏的黑客行为。
It's not possible to raise a C#
event
directly from anotherclass
(even if it'spublic
). You could provide a method (with a sufficient access modifier) that raises theevent
on your behalf and call that method in the otherclass
.By the way, this is possible with reflection, but I consider that a dirty hack.
CLR 中引发事件的大多数类型都有一个受保护的 On[EventName] 方法来负责引发事件。 您可以使用反射“从外部”调用此受保护的方法:
Most types in the CLR that raises events has a protected On[EventName] method that takes care of raising the event. You can invoke this protected method "from the outside" using Reflection:
我使用反射和扩展方法实现了这一点,这样我就可以通过调用(在本例中)调用 LinkLabel 单击事件:
click() 方法是一个 C# 扩展方法:
它使用另一个扩展方法来:
I implemented this using reflection and extension methods so that I can just invoke (in this case) a LinkLabel click event by just calling:
the click() method is an C# extension method:
which uses another extension methods to:
根据您使用的框架,您可能不必手动调用父级上的单击事件,WPF 和 ASP .NET 例如,将事件冒泡到元素树中。
如果这不是一个选择,你可以像迈赫达德建议的那样做。
Depending on what framework you are using its possible you don't have to manually invoke the click event on the parent, WPF and ASP.NET for example bubble events up the element tree.
If that's not an option you can do like Mehrdad suggests.
我能想到的您想要引发 Click 事件的唯一原因是您是否正在模拟用户输入。 您正在开发自动测试驱动程序或类似的东西吗? 如果是这样,可能有比用仅测试辅助方法玷污代码更好的解决方案。 这个首先出现在谷歌中,我不知道它是否有好处。
如果您尝试将其作为应用程序本身的一种流量控制,我会退一步看看这是否是正确的做法 - 它有点“闻起来很糟糕”。
The only reason I can think of for why you would want to raise the Click event is if you are simulating user input. Are you working on an automated test driver or something like that? If so, there may be better solutions than sullying the code with test-only auxiliary methods. This comes up first in google, I have no idea if it's any good.
If you're trying to do this as a kind of flow control in your application itself, I'd take a step back to see if this is the right thing to do at all - it kind of "smells bad".