指定从基本形式到继承形式的属性
我有 ac# winform,它是我项目中所有表单的模板。
我的问题是如何为将从基本表单继承的表单中添加的控件设置一些属性。 例如,我希望表单中的所有文本框都具有特定的颜色,或者调用扩展方法。
现在,我尝试了弹出的简单想法:
foreach (Control c in Controls)
{
if(c is ComboBox)
{
//do something
}
if(c is TextBox)
{
//do something
}
}
我将此代码放入基本表单加载事件中,但没有运气。我尝试将修饰符从继承形式更改为受保护形式,但没有成功。
这个问题有什么解决办法吗?或者我有义务将此代码放入我所有继承 baseForm 的表单中?
I have a c# winform that is a template for all the forms in my project.
My problem is how do I setup some properties for the controls that will be added in the inherited forms from the baseform.
For example I want all the textboxes that will be in the forms to have a specific color, or call an extension method.
Right now I tried the simple idea that popped out:
foreach (Control c in Controls)
{
if(c is ComboBox)
{
//do something
}
if(c is TextBox)
{
//do something
}
}
I put this code in the base form load event, but with no luck. I tried changing the modifiers from the inherited form to protected, but with no luck.
Is there any solution to this problem? Or I am obliged to put this code in all of my forms that inherit baseForm?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自定义控件是您手头问题的解决方案。只需扩展现有控件以具有您想要的属性,然后您就可以在所有表单中使用这些控件。
Custom Controls are the solution to the problem you have at hand. Simply extend existing Controls to have attributes of your desire and then you could these controls in all of your Forms.
你开始沿着正确的思路思考,但还没有完全实现。解决这个问题的方法肯定是面向对象的继承,但是你必须小心,不要违反 OOP 的其他重要原则,即封装。
换句话说,表单不应该被要求“了解”它所包含的控件的属性。它不应该知道或关心它包含 ComboBox、TextBox 或 ListView。
相反,您应该对要修改的每个子控件进行子类化,并在那里设置它们的默认属性。然后,您只需将自定义子类控件的实例(而不是内置控件)添加到表单中。
因此,例如,您的自定义 TextBox 类可能如下所示:
You're beginning to think along the right lines, but you're not quite there yet. The solution to this problem is definitely object-oriented inheritance, but you must be careful not to violate other important principles of OOP, namely encapsulation.
To put things a different way, the form should not be required to "know" about the properties of the controls that it contains. It shouldn't know or care that it contains a ComboBox or a TextBox or a ListView.
Instead, you should subclass each of the child controls that you want to modify, and set their default properties there. Then, you would just add an instance of your custom subclassed control to your form, rather than the built-in control.
So, for example, your custom TextBox class might look like this: