WPF

WPF ListView ItemTemplate Tutorial

WPF provides various templates for customization of controls. WPF ListView ItemTemplate is in one of these. ItemTemplate of ListView is useful when we have to change the visual presentation of bound data objects.

If your WPF ListView control is bound to collection of objects using ItemsSource proeprty and you have not set the ItemTemplate property, then it will call the ToString() method of each bound object and whatever is returned by the method it will display in the ListView.

If you want to customize the display of items, then you must set the DataTemplate by using ItemTemplate property.

Below is the simple example, in which I set the DataTemplate using ItemTemplate property of WPF ListView.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView x:Name="MyListView" ItemsSource="{Binding Employees}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock  Text="{Binding Id}" />
                        <TextBlock  Text="{Binding Name}" Margin="5,0,0,0" />
                        <TextBlock  Text="{Binding Age}" Margin="5,0,0,0" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<Employee> employees;

        public MainWindow()
        {
            InitializeComponent();
            employees = new List<Employee>();
            employees.Add(new Employee { Id = 1, Name = "Kapil Malhotra", Age = 30 });
            employees.Add(new Employee { Id = 2, Name = "Raj Kundra", Age = 34 });
            employees.Add(new Employee { Id = 3, Name = "Amitabh Bachan", Age = 80 });
            employees.Add(new Employee { Id = 4, Name = "Deepak Khanna", Age = 72 });

            this.DataContext = this;
        }

        public List<Employee> Employees
        {
            get
            {
                return employees;
            }
        }
    }

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
ListView Example