将相同的事件应用于 C# 中的每个项目按钮 [英] Apply same event to every project button in a C#

查看:21
本文介绍了将相同的事件应用于 C# 中的每个项目按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 个表单和 10 个用户控件的项目.这些组件中的每一个都有大约 10 个按钮.当用户悬停时,我想使用一个事件来应用样式.有没有办法可以为通用组件创建此事件,然后它会自动应用于每个组件?因为我不一定有心情手动经历130个按钮事件^^

I have a project with 3 forms and 10 user controls. Each of these components has around 10 buttons. I would like to use an event to apply a style when they are hovered by the user. Is there a way that I can create this event for the general component and then it would be applied to each component automatically? Because I am not necessarily in the mood to go through 130 buttons event manually ^^

推荐答案

您最好的选择可能是将按钮类子类化,并在您的其余代码中使用它.反映所有表单和用户定义的控件以识别每个按钮并将事件处理程序添加到每个按钮将是昂贵的(就开发人员时间和运行时间而言).由于 Button 类 未密封,您可以轻松覆盖 OnMouseHover() 方法根据需要更新按钮(确保在离开覆盖之前调用基类方法).

Your best option probably would be to subclass the button class, and use that throughout the rest of your code. Reflecting through all your forms and user-defined controls to identify and add an event handler to each button will be costly (both in terms of developer time and run time). Since the Button class isn't sealed, you can easily override the OnMouseHover() method to update the button as needed (making sure to call the base class method before leaving your override).

这篇关于将相同的事件应用于 C# 中的每个项目按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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