Over a million developers have joined DZone.

Using DataTemplate for Visualizing a Single Item


Data templating is a powerful visualization mechanism used primarily for displaying a large number of objects. Controls such as LongListSelector or ListBox display each item from the bound collection using the appropriate DataTemplate.

But if you have a single instance of some class that has a DataTemplate created for it, you can still use your data templates for visualization. For that we will use ContentControl.

Let’s say we have the following view model defined in code:

public class SomeViewModel
    public string Data { get; set; }

    public SomeViewModel()
        Data = "Hello";

The binding setup is really simple (for the purpose of keeping this demo simple):

public partial class MainPage
    public SomeViewModel Some { get; set; }

    public MainPage()

        Some = new SomeViewModel();
        DataContext = this;

The definition of the data template in XAML:

<DataTemplate x:Key="SomeTemplate">
	<TextBlock Text="{Binding Data}" />

To use the data template with the ContentControl control, we bind the property from the data context using theContent property and we set the data template using the ContentTemplate property.

<ContentControl ContentTemplate="{StaticResource SomeTemplate}"
				Content="{Binding Some}" />

The final result is this:

The property is bound to ContentControl and is using our DataTemplate

That’s it. This really simple sample demonstrates how to reuse DataTemplates in single item scenarios without needlessly using items control. The source code can be found over at GitHub.


Published at DZone with permission of Toni Petrina , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}