As this article is only meant to be a brief introduction to designers, we won't make anything terribly complicated. Before we can make a designer we need a control to design, so we'll create a simple usercontrol that draws an ellipse in its client area.
To create a custom designer for a control you will either inherit from ControlDesigner
or ParentControlDesigner
, depending on whether you want users to be able to place child controls in your control. All we need for this article is to inherit from ControlDesigner
. You will need to add an assembly reference to System.Design.dll
to see these classes. To associate your designer class with your control, you use the DesignerAttribute
class:
[VB]
Imports System.Windows.Forms.Design
Imports System.ComponentModel
<Designer(GetType(MyControlDesigner))> _
Public Class UserControl1
Inherits System.Windows.Forms.UserControl
Public Sub New()
MyBase.New()
SetStyle(ControlStyles.ResizeRedraw, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.DoubleBuffer, True)
End Sub
Private Sub UserControl1_Paint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
e.Graphics.DrawEllipse(Pens.Red, ClientRectangle)
End Sub
End Class
Friend Class MyControlDesigner
Inherits ControlDesigner
End Class
[C#]using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace CSharpTest
{
[Designer(typeof(MyControlDesigner))]
public class UserControl1 : System.Windows.Forms.UserControl
{
public UserControl1()
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
this.Paint += new PaintEventHandler(UserControl1_Paint);
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawEllipse(Pens.Red, ClientRectangle);
}
}
internal class MyControlDesigner : System.Windows.Forms.Design.ControlDesigner
{
}
}
In the Form designer, you should see the UserControl you just created in the toolbox, and you can drag it on to the form like you would any other control. Although our designer class doesn't do anything yet, the instance on the form is using it.
Comments