Data Templates
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.
Getting ready
Let's create a new project using the template Ch1_Recipe
and rename it as Ch1_Recipe3
.
How to do it...
In this recipe we will give priority to the ListBox control.
Open the
MainPage.xaml
file, locate theGrid
with the nameContentPanel
and add aTextBlock
and aListBox
after the last text block control. TheListBox
control will containItemTemplate
in whichDataTemplate
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>
Let's initialize the
Listbox
in the code behind theXAML
file,MainPage.xaml.cs
, using theItemsSource
property of theListBox
.ItemSource
is a collection property. Add the following code inside theMainPage
constructor before the initialization:lstPriority.ItemsSource = new string[] { "Low", "Medium", "High" };
Press F5 to see how the
ListBox
is filled withLow
,Medium
, andHigh
values. Also, notice how theListBox
behavior changes with theBorder
style.
How it works...
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.
There's more...
To understand more on Data Templates check the following article:
See also
Check the recipe named DataContext to understand more on data context concepts.