开发者

Specify properties from baseform towards inherited ones

开发者 https://www.devze.com 2023-03-29 11:25 出处:网络
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.

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?


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.


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:

public class CustomTextBox : TextBox    // inherit from TextBox
{
    public CustomTextBox()
    {
        // default constructor
    }

    // other logic...

}
0

精彩评论

暂无评论...
验证码 换一张
取 消