Data Templates are a very powerful feature in XAML. Data Templates can be reusable within element level or application level. In this recipe, let's use the Data Template in the listbox control.
MainPage.xaml
file, locate the Grid
with the name ContentPanel
and add a TextBlock
and a ListBox
after the last text block control. The ListBox
control will contain ItemTemplate
in which DataTemplate
is added.<!-- List box priority --> <TextBlock x:Name ="tbPriority" Text ="Priority:" Grid.Row="3" Grid.Column ="0" /> <ListBox x:Name ="lstPriority" Grid.Row="3" Grid.Column ="1"> <ListBox.ItemTemplate> <DataTemplate> <Border Name="border" BorderBrush="Red" BorderThickness="1" Padding="5" Margin="5"> <StackPanel> <TextBlock x:Name ="tbPriorityContent" Text ="{Binding}" /> </StackPanel> </Border> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Listbox
in the code behind the XAML
file, MainPage.xaml.cs
, using the ItemsSource
property of the ListBox. ItemSource
is a collection property. Add the following code inside the MainPage
constructor before the initialization:lstPriority.ItemsSource = new string[] { "Low", "Medium", "High" };
ListBox
is filled with Low, Medium
, and High
values. Also, notice how the ListBox
behavior changes with the Border
style.A Data Template is the most flexible way to display data in XAML. It can include all the XAML controls like button, text blocks, textboxes, data grid, and so on. Here in the ListBox
control, a Data Template is applied to all the items in the listbox along with all the formatting properties. We applied the Red
border to the items in the DataTemplate
mark-up.