Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Saturday, July 7, 2012

The differences between CustomControls and UserControls

WPF has two concepts of controls: UserControls and CustomControls. But what's the difference between them? In this article I try to list the characteristics of each of them to help you to choose the right type for your project.

UserControl (Composition)

  • Composes multiple existing controls into a reusable "group"
  • Consists of a XAML and a code behind file
  • Cannot be styled/templated
  • Derives from UserControl
This example of an "RGB user control" composes three labels and textboxes as well as a color field together to an reusable part. The logic in the code behind file adds a Color DependencyProperty that gets and sets the resolved color.

CustomControl (Extending an existing control)

  • Extends an existing control with additional features
  • Consists of a code file and a default style in Themes/Generic.xaml
  • Can be styled/templated
  • The best approach to build a control library
This example of a "Numeric up/down" control is an extension of a textbox. The up and down buttons are defined in the default template of the control and wired up in the OnApplyTemplate() override in the logic part of the control. The ControlTemplate can easily be exchanged by another that has the up,down buttons aligned left for example.

No comments:

Post a Comment