WPF: Displaying more properties of a class in a ListBox

This entry is part 33 of 54 in the series Learn WPF

In the previous example, we only display the LastName property of the Customer class.  To display all properties in the ListBox, we need to make some modifications to the MainWindow.xaml.

Here we need to set the ItemTemplate property to the DataTemplate that formats the items.

<Window x:Class="ListBoxNSpace.MainWindow"
        Title="MainWindow" Height="350" Width="525">
            <src:Customers x:Key="customers"/>
        <ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Padding="5,0,5,0"
          Text="{Binding FirstName}" />
                        <TextBlock Text="{Binding LastName}" />
                        <TextBlock Text=", " />
                        <TextBlock Text="{Binding Address}" />


using System;
using System.Collections.Generic;
using System.Windows;
using System.Collections.ObjectModel;

namespace ListBoxNSpace
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public class Customer
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Address { get; set; }

        public Customer(String firstName, String lastName, String address)
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Address = address;

    public class Customers : ObservableCollection<Customer>
        public Customers()
            Add(new Customer("Michael", "Anderberg",
                    "12 North Third Street"));
            Add(new Customer("Chris", "Ashton",
                    "34 West Fifth Street"));
            Add(new Customer("Cassie", "Hicks",
                    "56 East Seventh Street"));
            Add(new Customer("Guido", "Pica",
                    "78 South Ninth Street"));

    public partial class MainWindow : Window
        public MainWindow()

Notice that in line 37, class Customers is derived from the generic class ObservableCollection with class Customer as the type parameter.



Series Navigation<< WPF: Specify the property to display in ListBox
WPF: Using instance name for ListBox >>

Leave a comment

Leave a Reply