WPF: Using instance name for ListBox

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.

MainWindow.xaml
<Window x:Class="ListBoxNSpace.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>
        <ListBox Name="lb" Width="350" Margin="0,5,0,10">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Padding="5,0,5,0" Text="{Binding FirstName}" />
                        <TextBlock Text="{Binding LastName}" />
                        <TextBlock Text=", " />
                        <TextBlock Text="{Binding Address}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

</Window>
MainWindow.xaml.cs
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()
        {
            InitializeComponent();

            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;
          
        }
    }
}

instancelistbox

 

 

 

 

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