WPF - Custom Control VS User Control
In WPF what is the difference between a Custom Control and a User Control? This is pretty basic stuff but I hear this question being asked a LOT so figured I’d do a quick post on the subject.
A user control is essentially the composition of various controls into one larger control allowing a whole group of controls to be reused. It is extremely similar to creating a Window/Page in WPF – you have access both to the XAML markup and the code-behind and can employ the same techniques (drag/drop, declaratively through XAML) when adding child controls.
If you have an ASP.NET background this will seem extremely similar to an ASCX control – which it is. Both are used to partition common user interface components and allow them to be reused as a single unit in the future. As an example, take the following address input mockup. The user may be asked to enter their address when registering an account with the application/choosing a delivery address for a product/choosing a billing address for a product/etc. The control itself is exceedingly straightforward – it contains 6 labels, 4 textboxes and 2 combo boxes. The question is, do you want to duplicate the markup and behavior behind these fields every time you need a user to input their address? Probably not…this is where a user control comes in handy!
A custom control, on the other hand, acts as an extension point for existing control. You do not have access to the markup but instead add extra functionality to the control using themes and user defined templates. The magic of custom controls is that you are able to inherit from a wide range of existing controls. Therefore, if a control fulfills 90% of your needs, you can base a custom control on this existing control and build your additional behavior on top of it.
For instance, imagine (if you can) a textbox that displays your total word count. Obviously 99% of the work is the creation of the textbox – the rest is easy. A custom control would allow us to define a new CountingCheckBox (I came up with the name all by myself) control deriving all of the features of a regular textbox.Custom controls, unlike user controls have the added benefit of being theme-able, making them the more appropriate choice when creating suites of controls.
And that is that!