WPF: Add new data with notification

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

Following the previous example, we can add new data to the list and have the UI display the updated list immediately.

To do that we need to allow notification by using ObservableCollection.  In the previous example, we have used a generic list for the Person class.

Now we need to replace the List<Person> with ObservableCollection<Person>.

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>     
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ListBox x:Name="lb" DisplayMemberPath="Name" Grid.Row="0" />
        <Button Content="Add" Click="OnAdd" Grid.Row="1" />
    </Grid>
</Window>

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

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

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

        ObservableCollection<Person> people = new ObservableCollection<Person>  {
              new Person { Name = "Michelle", Age = 10 },
              new Person { Name = "Emily", Age = 45 },
              new Person { Name = "John", Age = 35 }
            };

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

        private void OnAdd(object sender, RoutedEventArgs e)
        {
            people.Add(new Person { Name = "Lisa", Age = 22 });
        }
    }
}

notification

Series Navigation<< WPF: DisplayMemberPath
WPF: Data Template >>

Leave a comment

Leave a Reply