WPF: Binding to a collection

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

Using the ListBox, we show another example on how we can bind a class’s properties to a collection.

ListBox is one of those controls that can display multiple data objects.  With the help of data templates and value converters, it can become a powerful visualization tool.

MainWindow.xaml
<Window x:Class="ListBoxBinding.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 x:Name="lb">
        </ListBox>
    </Grid>
</Window>

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

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

        List<Person> people = new List<Person> {
              new Person { Name = "Michelle", Age = 10 },
              new Person { Name = "Emily", Age = 45 },
              new Person { Name = "John", Age = 35 },
              new Person { Name = "Lisa", Age = 12 },
              new Person { Name = "Maggie", Age = 1 }
            };

        public MainWindow()
        {
            InitializeComponent();
            lb.ItemsSource = people;
        }
    }
}

Person.cs
namespace ListBoxBinding
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return string.Format("{0} is {1} years old", Name, Age);
        }
    }
}

collectionbinding

 

 

 

 

 

Series Navigation<< WPF: Adding and deleting items in DataGrid
WPF: DisplayMemberPath >>

Leave a comment

Leave a Reply