When to use a templated control over a UserControl?

TLDR

A custom (templated) control allows an app to use the Template property to replace the control’s internal element tree. If you don’t need/want your control to have that re-templating feature, then use a UserControl as it’s easier.

UserControl

  • A UserControl is a lot easier to create with Visual Studio or Blend giving you a decent design view support.
  • You typically use it to compose a view in your app from multiple controls.’
  • It works best for full screen or full-window views or if you have complex views that you want to break apart in smaller, possibly reusable code chunks.
  • Such view is often backed with a corresponding view model if you choose to adopt the MVVM pattern.

  • One problem with a UserControl is that while you can reuse it in multiple places in your app – it is difficult to make slight adjustments to the way it looks or behave in different places in your app since it doesn’t use templates and the UI tree is loaded in the constructor.

  • It is typically only reusable within the scope of the single app.

Custom control

  • A custom control or in some cases templated control is best suited for a small chunk of UI that serves a single purpose – it visualizes a single, specific type of information.
  • A templated control can have its template changed to adjust the visuals for particular use case. It allows you to have a button that looks like a default button in one app, a rounded one in another and one made solely up of images in yet another. It makes it more reusable which makes sense if you make more than one app or want to share your awesome control with the world.
  • A well written custom control is usually reusable in more than one app since it doesn’t depend on business logic of particular app.
  • It typically derives from an existing platform control, such as Button, ToggleButton, ContentControl, Slider, TextBox or ListView to add to or override its logic. There are cases though when it makes sense to make one from scratch, subclassing “virtually abstract” Control, ItemsControl, RangeBase, Shape or even FrameworkElement (the last two are not templated).
  • The visual tree of a templated control is loaded when the template is loaded which might occur as late as when the control’s visibility is first changed from Collapsed to Visible which allows to defer loading parts of your UI to get performance improvements.
  • Because the control template is only loaded once, these are ideal for use inside any ItemsControl DataTemplate (lists, gridviews, etc). If you were to use a UserControl, your performance could really suffer because the UserControl XAML is parsed over and over again.

Custom panel

A custom panel is yet another type of UI element that allows to customize how it lays out its children.

Leave a Comment