ObservableCollection is a dynamic data collection with automatic notifications when items are added, removed, or updated.
Example: Very simple ObservableCollection
In this example we will create a new class named Person and a list of persons using ObservableCollection. Using a DataGrid we will set only a property ItemsSource. When press Add button the grid is automatically update. Please also see OnCollectionChanged event in which we can display some status of operations.
XAML:
<Label Content="First Name" HorizontalAlignment="Left" Margin="9,0,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="txtFname" HorizontalAlignment="Left" Height="23" Margin="10,26,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="216"/>
<Label Content="Last Name" HorizontalAlignment="Left" Margin="10,59,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="txtLname" HorizontalAlignment="Left" Height="23" Margin="11,85,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="215"/>
<Button x:Name="btnAdd" Content="Add" HorizontalAlignment="Left" Margin="151,127,0,0" VerticalAlignment="Top" Width="75" Click="btnAdd_Click"/>
<DataGrid x:Name="dgPerson" HorizontalAlignment="Left" Margin="242,10,0,0" VerticalAlignment="Top" Height="300" Width="552"/>
<Label x:Name="lblStatus" Content="" HorizontalAlignment="Left" Margin="0,284,0,0" VerticalAlignment="Top" Width="226"/>
</Grid>
C# Code:
public partial class MainWindow : Window
{public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
private ObservableCollection<Person> persons = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
dgPerson.ItemsSource = persons;persons.CollectionChanged += this.OnCollectionChanged;
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){
//Get the sender observable collection
ObservableCollection<Person> obsSender = sender as ObservableCollection<Person>;
NotifyCollectionChangedAction action = e.Action;
if (action == NotifyCollectionChangedAction.Add)
lblStatus.Content = "New person added";
if (action == NotifyCollectionChangedAction.Remove)
lblStatus.Content = "Person deleted";
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Person p = new Person();
p.FirstName = txtFname.Text;
p.LastName = txtLname.Text;
persons.Add(p);
}
}