Can anyone please explain ItemTemplate.DataTemplate
and ListView
. In this code snippet.
I really don't understand the concept of Templates
, it will be help full if someone might put some light on that too.
I had look to this question:
Metro app: ListView ItemTemplate DataTemplate for selected item
But still confused. Thank you! :(
<ListView Margin="10" Name="lvDataBinding">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="Name: " />
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<TextBlock Text=", " />
<TextBlock Text="Age: " />
<TextBlock Text="{Binding Age}" FontWeight="Bold" />
<TextBlock Text=" (" />
<TextBlock Text="{Binding Mail}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
<TextBlock Text=")" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ListView is a control that allows you to dynamically show a list of items so that users can scroll through that list of items to see them and find whatever they may need. It's really simple to define it in XAML:
Now, let's say you have a list of university students. Every student is represented with a simple Student class.
There could be dozens, hundreds or thousands of students, so you can't define the UI statically. You usually keep those students in some sort of list/collection in code-behind. You fetch them from various sources - database, web services, or hard-code it, like I will do now for demo purposes:
That list/collection serves as an items source for the ListView, so you set the
ItemsSource
property of the ListView to connect the two and show the list in UI. Using a ListView all the items are rendered dynamically regardless of the number of items.If we ran the app now, it would be pretty ugly though:
You need to define a
DataTemplate
to make it prettier. Since each and every student has a name and age, you will want to use those properties to make it look prettier. ThisDataTemplate
is assigned toListView.ItemTemplate
property and the ListView will use it for each and every item in the list.See, I used the DataTemplate to define which properties to show and how to render them - I played with font size, font colors, margins etc. I'll admit this isn't really that pretty, but I am sure you will get the point:
One more thing you'll notice is that I used a binding construct like this:
This basically means: Check if the object has the property
Name
and if it does, render it asTextBlock.Text
.Note that things can get more complicated so you could use different templates for different items in one list etc. but that's not in the question scope I think.
TLDR:
ListView
dynamically renders a list of items.ItemsSource
defines the items source for thatListView
.DataTemplate
defines a template that will be used to render something. ThisDataTemplate
is assigned toItemTemplate
property of theListView
so that theListView
knows that it should use exactly that template to render its items.