logo       

Re: User v Custom Controls: msg#00370

windows.devel.dotnet.winforms

Subject: Re: User v Custom Controls

Richard Heintze schrieb:
> > How do I decide between user and custom controls?

Fabian Schmied replied:
> User controls are derived from UserControl and thus inherit the
> infrastructure to contain other controls

But UserControl inherits *that* infrastructure from Control... So this
is doesn't really help you in deciding between a custom control and a
user control - custom control can contain other controls too. (So can
any control actually. The Forms Designer prevents you from setting up
some of the more stupid containment relationships - for example, it
won't let you drag a control inside of a Button. But you can add
children to a Button control in code.)

The big difference is that the UserControl has visual designer support.
You can edit it like a form. The design surface VS.NET shows for a
custom control only shows a component tray, not a full visual drag and
drop view like you get with Forms and UserControls.

(UserControl also has focus handling and scrollability, but that's only
because it derives from ContainerControl, which in turn derives from
ScrollableControl. If you want these features in a custom control, you
can derive from those base classes.)


> Custom controls inherit from Control and thus have
> no container facilities.

This is easily disproved:

public class MyCustomControl : Control
{
public MyCustomControl()
{
Button childButton = new Button();
childButton.Text = "Child!";
childButton.Location = new Point(10, 20);
childButton.Size = new Size(100, 100);
this.Controls.Add(childButton);

// and for my next trick...

Button buttonInButton = new Button();
buttonInButton.Text = "Grandchild!";
buttonInButton.Location = new Point(3, 3);
childButton.Controls.Add(buttonInButton);
}
}

That's a custom control that contains a child button. (And just to
prove it can be done, the child button itself contains a child button!)
No need to derive from UserControl. (You don't even need to derive from
ContainerControl to be able to contain children. ContainerControl is a
slightly confusingly named class - it's mainly about handling focus in
composite controls.)

DataBinding also works just fine in custom controls. The only thing
UserControl gives you is the ability do design the control visually.


--
Ian Griffiths - DevelopMentor
http://www.interact-sw.co.uk/iangblog/



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise