.NET Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 69 posts at DZone. You can read more from them at their website. View Full User Profile

Using DataTemplate for Visualizing a Single Item

  • submit to reddit

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, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)