WPF

WPF ListView Binding

WPF Listview is a control that is used for display a list of data items. It inherits directly from ListBox. Listview provides an ItemsSource property for binding list of items. Below is the sample program for binding listview items.

<Window x:Class="WpfApplication5.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" />
    </Grid>
</Window>
namespace WpfApplication5
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var users = new List<User>();
            for (int i = 0; i < 10; ++i)
            {
                users.Add(new User { ID = i, Name = "Name " + i.ToString(), Age = 20 + i });
            }

            myListView.ItemsSource = users;
        }
    }

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return this.Name.ToString();
        }
    }
}

wpf-listview

In above line 15, I have bind Listview control to list of users using ItemsSource property.

But in the above example, it only shows only one property of user which I have shown by overriding the User ToString() method. Because by default Listview only show the data returned by ToString() method of class bind to it.

For showing more than one property of User class, we need to use DataTemplate. Every Listview item is contained in ListViewItem control and DataTemplate defines a UI for the ListViewItem control.

We can assign DataTemplate to ItemTemplate property of ListView.

<Grid>
	<ListView x:Name="myListView">
		<ListView.ItemTemplate>
			<DataTemplate>
				<StackPanel Orientation="Horizontal">
					<TextBlock Text="{Binding ID}" />
					<TextBlock Text=" " />
					<TextBlock Text="{Binding Name}" />
				</StackPanel>
			</DataTemplate>
		</ListView.ItemTemplate>
	</ListView>
</Grid>

In the above example, I have create a DataTemplate which show two properties ID and Name of User class and assigned that DataTemplate into the ItemTemplate property.

WPF-ListView-DataTemplate-ItemTemplate