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.

 

Series Navigation<< WPF: Adding items to combobox using ObservableCollection
WPF: Defining an instance in XAML >>

Leave a comment

Leave a Reply