Using DataTemplate for Visualizing a Single Item
Join the DZone community and get the full member experience.
Join For FreeData 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() { InitializeComponent(); Some = new SomeViewModel(); DataContext = this; } }
The definition of the data template in XAML:
<DataTemplate x:Key="SomeTemplate"> <TextBlock Text="{Binding Data}" /> </DataTemplate>
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:
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. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments