65.9K
CodeProject is changing. Read more.
Home

A control for skinning groups of controls

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (4 votes)

Dec 18, 2006

CPOL

2 min read

viewsIcon

28730

downloadIcon

270

A control used to mass change other controls' properties.

Sample screenshot

Introduction

What is a skin control, you may ask? A skin control is a control that can change the properties of many other controls quickly. For instance, in an application, you want to have the ability to have a green color scheme, a blue color scheme, etc. By using this control, you can specify the property (either by name or built-in) and what you want to set the property as. Quick, easy, and saves a ton of code. Here's how...

How it Works

How does this code work. It is actually quite simple. Included are a couple of methods to change some common properties like Name, Backcolor, Forecolor, etc. Along with these, you can also say you only want certain types to change, like only change the Forecolor of controls of type Button. But what if you want to change the property of a custom control? Or one that isn't provided? Here is where Reflection comes in.

During run time, I don't explicitly know the type of the object given. So I have to use Reflection to get it, like so:

Dim objType As Type = ctrl.GetType()

This creates an object objType. The type of objType is that of the control ctrl. Then, we can get the property we want, given its name.

Dim propInfo As PropertyInfo = objType.GetProperty(PropertyName)

This gets the PropertyInfo of that object. By passing in the name of the property we want to change, we can get or set the property. All that's left is to change the property.

propInfo.SetValue(ctrl, val, Nothing)

ctrl is the control whose property we want to change. val is the new value. Nothing (null) is used for the index in the case of an array. I just threw this together, so I did not add the ability to change this. If there is enough demand, I can.

But Wait, There's a Catch...

In order to change the properties of the control, it must be passed ByRef(erence) to the skin control. This means that the skin control still hold a reference so the control cannot be GC'd. Calling the RemoveControl method will remove the reference to the control. That's about it. Hope this can teach a little bit about Reflection.