Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ContentControl and ContentPresenter?

I'm not sure when I should use ContentPresenter instead of ContentControl (and vice-versa). At the moment, I'm using ContentControl pretty much all the time in my DataTemplates. When would ContentPresenter be a better choice? and why?

like image 417
Wilka Avatar asked Oct 09 '22 12:10

Wilka


People also ask

What is ContentPresenter?

The concept of ContentPresenter is quite simple – it is a placeholder for any XAML content and it can be used to insert content at runtime. Or we can say that ContentPresenter is a class that will automatically take the content of the ContentControl and display it, when placed into a ContentControl's ControlTemplate.

What is a ContentControl?

Content Control is a base class that provides standardised functionality to WPF Controls. The Content Control class represents controls that can include a single item of content. This content is commonly plain text or a child control. Content Control is a subclass of the Control class in WPF.


1 Answers

ContentControl is a base class for controls that contain other elements and have a Content-property (for example, Button).

ContentPresenter is used inside control templates to display content.

ContentControl, when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content.

My rules of thumb (not applicable in every case, use your judgment):

  1. Inside ControlTemplate use ContentPresenter
  2. Outside of ControlTemplate (including DataTemplate and outside templates) try not to use any of them, if you need to, you must prefer ContentPresenter
  3. Subclass ContentControl if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).
like image 140
Nir Avatar answered Oct 23 '22 01:10

Nir