WPF: Using instance name for ListBox

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

In the previous example, we have used static resource for the data binding.

There is another method where we could display the data in the ListBox.  This is by defining an instance name for the ListBox.

In the example below, I have given the Name of the ListBox as lb.  In the code behind, we can add the properties such as the Name, Address to a list.  We need to use similar instance name lb for the list so that they could be mapped correctly.

<Window x:Class="ListBoxNSpace.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <ListBox Name="lb" 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.ObjectModel;
using System.Windows;

namespace ListBoxNSpace
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window

        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 MainWindow()

            List<Customer> cust = new List<Customer>();

            cust.Add(new Customer("Michael", "Anderberg", "12 North Third Street"));
            cust.Add(new Customer("Chris", "Ashton", "34 West Fifth Street"));
            cust.Add(new Customer("Cassie", "Hicks", "56 East Seventh Street"));
            cust.Add(new Customer("Guido", "Pi", "78 South Ninth Street"));

            lb.ItemsSource = cust;






Series Navigation<< WPF: Displaying more properties of a class in a ListBox
WPF: Listview with a gridview >>