开发者

Custom Control Constructors [duplicate]

开发者 https://www.devze.com 2023-03-08 00:58 出处:网络
This question already has answers here: 'UserControl' constructor with parameters in C# (10 answers)
This question already has answers here: 'UserControl' constructor with parameters in C# (10 answers) Closed 1 year ago.

Pardon me for this long story, but I think the question merits it.

I have a custom control that I made, which had it's own overridden OnPaintBackground method which used a member Brush and Pen. I was creating it like this:

CustomControl c = new CustomControl();
c.Parent = someParent;

and the constructor was just the default one with some added stuff for creating brushes and pens and stuff for the background.

However, I thought it would be nicer to have a constructor that took the parent panel (since my control can't be used without a parent) so I added one parameter to the constructor:

public CustomControl(Control parent) {
    InitializeComponent();
    Parent = parent;
    // do a bunch of stuff like getting brushes, pens, etc for drawing the background
}

Then when I ran my program, the first control was created and drawn fine. Then for all the controls after the first one, I was getting first chance exceptions in System.Drawing.dll and the backgrounds of all the panels inside my control were that red X that Winforms shows when it can't find an image or something. Remember though that the first instance of the control to be created was working perfectly.

So I set my Visual Studio to break when any exceptions were thrown instead of just logging it, and it broke on a line inside my overriden OnPaintBackground that looked like this :

e.Graphics.DrawLine(bPen, x, y, Width, Height);

With the information Argument cannot be null. So I looked in the debugger window and found that not only was bPen null, but all my brushes and pens and everything was null even though the constructor was being called (verified with a MessageBox)!

I eventually so开发者_Python百科lved the problem by removing the parameter from the default constructor and adding another seperate constructor that took an argument, and calling the default ctor from that one. However, I would like to know, what does C# have against controls not having a default constructor that makes them not able to create stuff like Pens?


There's some useful answers to this question: 'UserControl' constructor with parameters in C#


C# has nothing against controls, it doesn't care. It's just a language. Usually you will want a default constructor because the designer relies on them. In fact, something like this works just fine for me:

public class MyControl : Control
{
    private Control _parent;
    public MyControl()
    {
        InitializeComponent();
    }

    public MyControl(Control parent) : this()
    {
        _parent = parent;
    }
}
0

精彩评论

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