user4637563
user4637563

Reputation:

Why would you use DataTemplate in a ListView?

could someone please explain to me what is the difference if I use DataTemplate inside the ListView in XAML?

I have used ListView to display the content from my ObservableCollection without using DataTemplate and with DataTemplate it seems to look exactly the same?

Why then would I want to use Data Template? I would like to see a simple explanation/example.

Upvotes: 1

Views: 3521

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61339

DataTemplate is used to show data in ways beyond a simple text block. Sure doing this:

<ListView.ItemTemplate>
   <DataTemplate>
     <TextBlock Text="{Binding Name}"/>
   </DataTemplate>
</ListView.ItemTemplate>

Doesn't buy you much. But it allows you to do stuff like this:

<ListView.ItemTemplate>
   <DataTemplate>
     <StackPanel>
        <Image Source="{Binding ImagePath}"/>
        <TextBlock Text="{Caption}"/>
     </StackPanel>
   </DataTemplate>
</ListView.ItemTemplate>

Which is pretty cool! You can put anything inside the template, so it makes ItemsControl (and its derivatives) some of the most powerful classes in WPF.

Upvotes: 4

Asha
Asha

Reputation: 25

Please take a look at #HighCore's answer here WPF MVVM Why use ContentControl + DataTemplate Views rather than straight XAML Window Views?.

 <Window x:Class="MyViews.MainWindow"   
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:viewmodel="clr-namespace:Project.ViewModel" 
    DataContext="{Binding Main, Source={StaticResource Locator}}"
    Title="{Binding Title, Mode=TwoWay}"  Height="{Binding Height, Mode=TwoWay}" Width="{Binding Width, Mode=TwoWay}" Left="{Binding Left, Mode=TwoWay}" Top="{Binding Top, Mode=TwoWay}" WindowStartupLocation="CenterScreen">


<Window.Resources>     
    <HierarchicalDataTemplate DataType="{x:Type viewmodel:OtherViewModel1}">            
        <ContentPresenter Content="{Binding Path=Text}" />
    </HierarchicalDataTemplate>
    <DataTemplate DataType="{x:Type viewmodel:OtherViewModel2}">
        <view:ConnectivityLED />
    </DataTemplate>      
</Window.Resources>

So you can see Mainwindow is talking to more than 1 viewmodel, Main is its own view model which is its datacontext and it also has reference to otherviewmodel1 and otherviewmodel2. Hope this helps, Cheers!

Upvotes: -1

Related Questions