What is the difference between ContentPresenter and ContentControl?

If you look at these two classes in reflector, you will notice the main difference between them: ContentControl derives from Control, and ContentPresenter doesn’t.

ContentControl is a control that knows how to display content. If you’ve been reading my blog, you’re probably familiar with ItemsControl by now, which is a control that knows how to display a collection of data. ContentControl is the equivalent to ItemsControl, but it is used to display non-collections instead. Some classic examples of controls that derive from ContentControl are Button and Label. Its most important property is the Content DependencyProperty, of type object.

ContentPresenter is an element that is useful inside the template of a ContentControl, and is used to specify where you want its content to be placed. For example, in the markup above I placed a ContentPresenter inside the Border because I want the Content of the Button (”Hello”) to appear inside the Border. If you remove the ContentPresenter, you will notice that “Hello” is no longer displayed. If you add elements before or after, you will notice that “Hello” will show up in the location where the ContentPresenter is placed in the layout pass.

The ContentPresenter tag in the markup above is equivalent to the following:

    <ContentPresenter Content=”{TemplateBinding Content}” ContentTemplate=”{TemplateBinding ContentTemplate}” ContentTemplateSelector=”{TemplateBinding ContentTemplateSelector}” Margin=”10″/>

A long time ago, you had to be explicit about where the Content, ContentTemplate and ContentTemplateSelector properties came from. We decided to make this implicit because we realized this is what people want most of the time. If, for some reason, you don’t want to use the Content of your ContentControl in its template, and want to use some other data instead, you can set the Content property of the ContentPresenter explicitly. For example, try replacing the ContentPresenter in the markup above with the following:

    <ContentPresenter Content=”{TemplateBinding Background}” Margin=”10″/>

You will notice that the Button will display “#FF4682B4″ instead of “Hello”, even though we set its Content property to “Hello”.

In summary: ContentControl is a control that uses a template to display a single piece of content, and ContentPresenter is used to specify where the content should go in the ContentControl’s template.

 

website:http://www.beacosta.com/blog/?p=38

reflector:http://www.red-gate.com/products/reflector/

posted on 2008-10-15 15:02  oyl  阅读(564)  评论(0编辑  收藏  举报

导航