an ObservableCollection is a dynamic collection where items can be added, removed or be updated with an automatic notification of actions.
I will demonstrate how this works in a very simple example:
All i have is a window with a Button a TextBox and a ListView and each time you click the Button the text of the Textfield is added to the collection and the ListView gets updated automatically.
Code file:
public partial class Window1 : Window
{
private ObservableCollection<String> names = new ObservableCollection<String>();
public Window1()
{
InitializeComponent();
listView1.ItemsSource = names;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
names.Add(textBox1.Text);
}
}
All you need to do is set the ItemsSource of you ListView to the ObservableCollection with
listView1.ItemsSource = names;
and then add your text with the Add() Method of the ObservableCollection.
names.Add(textBox1.Text);
XAML File:<Window x:Class="Observablecolection.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListView Margin="138,6,10,8" Name="listView1"/>
<Button Height="53" HorizontalAlignment="Left" Margin="14,17,0,0" Name="button1" VerticalAlignment="Top" Width="113" Click="button1_Click">Button</Button>
<TextBox HorizontalAlignment="Left" Margin="12,118,0,110" Name="textBox1" Width="123" />
</Grid>
</Window>
Showing posts with label ItemsSource. Show all posts
Showing posts with label ItemsSource. Show all posts
Saturday, April 25, 2009
very simple ObservableCollection tutorial
Posted by Bernd van Velsen at 10:43 AM 0 comments
Labels: ItemsSource, ObservableCollection
Subscribe to:
Comments (Atom)