Martijn
Martijn

Reputation: 24789

Which design pattern is used to give a class extra properties?

When you have a TableLayoutPanel on your Form and you drag a Label into a cell, a few properties are available on the Label control. I think the same construction is used when you drag a Tooltip control on the form.

I'd like to know which design pattern is used to achieve this. Is this the decorator pattern?

Upvotes: 4

Views: 664

Answers (2)

quentin-starin
quentin-starin

Reputation: 26638

What you are seeing are called Extender Providers.

For example, when a ToolTip component is added to a form, it provides a property called ToolTip to each control on that form. The ToolTip property then appears in any attached PropertyGrid control. http://msdn.microsoft.com/en-us/library/ms171836.aspx

I can't think of a well-known pattern that describes how they work, exactly, but the mechanism is simple.

You must implement IExtenderProvider. The WinForms Designer will call CanExtend for each other control on the surface, and your extender can specify if it provides additional attributes for each control.

public interface IExtenderProvider {
    bool CanExtend(object extendee);
}

The actual attributes that other controls will be extended are declared using the ProvidePropertyAttribute and a method to provide the value.

Upvotes: 7

ColinE
ColinE

Reputation: 70142

No, this is not achieved through a design pattern. These properties are simply the public properties exposed by the control, these properties are added to the control via inheritence, i.e. they sub-class Control. The visual studio designer inspects the class which implements these controls to determine the properties they expose, then provides you with a UI for setting them.

Upvotes: 1

Related Questions