Wednesday 17 September 2014

ObservableCollection Example

ObservableCollection is a built in collection type that raises change notification if any element in the collection is changed or deleted or a new element is added to the collection. If we want to create a custom collection type that raises change, we need to use INotifyCollectionChanged.

Below is a simple example of using ObservableCollection:
private ObservableCollection<string> names = new ObservableCollection<string>() { "aaa", "bbb", "ccc" };

public MainWindow()
{
 InitializeComponent();
 
 listBox1.ItemsSource = names;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
 names.Add(textBox1.Text);
        names[0] = "ABC";
}
and on the view:
<ListBox x:Name="listBox1" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" />
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23"  TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Content="Add Name" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="100" Click="Button_Click"/>            

No comments: