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.

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

 

 

 

 

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.

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"
        xmlns:src="clr-namespace:ListBoxNSpace"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <src:Customers x:Key="customers"/>
        </Grid.Resources>
        <ListBox ItemsSource="{StaticResource customers}" 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.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()
        {
            InitializeComponent();
        }
    }
}

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

listbox2

 

WPF: Specify the property to display in ListBox

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

There are many ways to display data in a ListBox control.  As in the earlier example, we set the ItemsSource property to the collection we want to display.

Optionally, we can set the DisplayMemberPath to specify the property to display in the ListBox.

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"
        xmlns:src="clr-namespace:ListBoxNSpace"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <StackPanel.Resources>
            <src:Customers x:Key="customers"/>
        </StackPanel.Resources>
        <ListBox ItemsSource="{StaticResource customers}" Width="250" Margin="0,5,0,10" SelectedIndex="3"
       DisplayMemberPath="LastName"/>
    </StackPanel>
</Window>

 

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;

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()
        {
            InitializeComponent();
        }
    }
}

listbox1

 

WPF: Adding items to listbox

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

We have been able to add items to a combo box using ObservableCollection class.

Using the same technique, we can add items to a ListBox from code behind.  This is really useful if the list items depend on what is available in the database.

MainWindow.xaml
<Window x:Class="ListBox2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:ListBox2"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel  Grid.Column="0"
             Grid.Row="6">
        <StackPanel.Resources>
            <src:VacationSpots x:Key="myVacations"/>
        </StackPanel.Resources>
        <ListBox Name="listBox" ItemsSource="{StaticResource myVacations}" SelectedIndex="1" Margin="50,50,50,50"/>

        <TextBlock Text="{Binding ElementName=listBox, Path=SelectedItem}" Margin="50,10,50,50"/>
    </StackPanel>
</Window>

MainWindow.xaml
using System.Collections.ObjectModel;
using System.Windows;

namespace ListBox2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    class VacationSpots : ObservableCollection<string>
    {
        public VacationSpots()
        {
            Add("Spain");
            Add("France");
            Add("Peru");
            Add("Mexico");
            Add("Italy");
        }
    }
}

listbox_item

 

As I have put SelectedIndex=”1″, this causes France to be the default selected item in the list.

 

WPF: Selecting An Item In Listbox

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

A list box is like a drop down list except that more than one item in the list box is visible.

If you look at the formation of a list box in the XAML, it is actually formed by a nested list of ListBoxItem.

MainWindow.xaml
<Window x:Class="ListBox1.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">
    <StackPanel Margin="50,50,50,50">
        <TextBox Name="tb" Width="140" Height="30"></TextBox>
        <ListBox Name="lb" Width="100" Height="55" SelectionChanged="DisplayOutput" SelectionMode="Single">
            <ListBoxItem>Item 1</ListBoxItem>
            <ListBoxItem>Item 2</ListBoxItem>
            <ListBoxItem>Item 3</ListBoxItem>
            <ListBoxItem>Item 4</ListBoxItem>
            <ListBoxItem>Item 5</ListBoxItem>
            <ListBoxItem>Item 6</ListBoxItem>
        </ListBox>
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace ListBox1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void DisplayOutput(object sender, SelectionChangedEventArgs args)
        {
            ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
            tb.Text = "   You selected " + lbi.Content.ToString() + ".";
        }
    }
}

As ListBox contains nested ListItemBox, we need to pay attention to line 30.

The object sender that is sent into the DisplayOutput method needs to be first converted to a ListBox.  We need to make another casting to ListBoxItem in order to print out the selected item in the list.

ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);

Below here the output from running the code above:

listbox