ItemsPresenter

In the last article in the WPF tutorial we saw how to add a ContentPresenter to a control template to act as a placeholder for the content of a ContentControl. This is important because the content of a control can be of many different types. With the ContentPresenter, we can ignore the type and allow the framework to render the content.

A similar problem exists with templates for controls that inherit from ItemsControl. This class includes a collection of objects in the Itemsproperty. These items are rendered according to a data template but we need to be able to specify the container for the output items. You can do so using an ItemsPresenter.

As with ContentPresenter, ItemsPresenter inherits functionality from the FrameworkElement class. However, you do not have to set any specific properties if you just want to use it as a simple placeholder for the items.

To demonstrate the creation of a control template for an ItemsControl we need a sample project. Create a new WPF application in Visual Studio named, "ItemsPresenterDemo". Once the environment is prepared, replace the XAML in the main window with the following code:

The template includes two Borders with slightly different margins and different background colours. This is to give the impression of a border with a shadow. The second border, which will be in front of the first, holds the ItemsPresenter that is the placeholder for the collection of items. In this case, a margin of ten device-independent units around the ItemsPresenter will separate the items from the border's edge.

Apply the control template to the ItemsControl by updating its XAML, as follows: