How to: Add Data to an ItemsControl
ItemsControl has a settable, ItemsSource property which allows one to add data to an ItemsControl. The items in an ItemsControl are of type ItemCollection. This example demonstrates how to create an ObservableCollection named Colors that is added to a ListBox.
Example
public class myColors : ObservableCollection<string>
{
public myColors()
{
Add("LightBlue");
Add("Pink");
Add("Red");
Add("Purple");
Add("Blue");
Add("Green");
}
}
Public Class myColors
Inherits ObservableCollection(Of String)
Public Sub New()
Add("LightBlue")
Add("Pink")
Add("Red")
Add("Purple")
Add("Blue")
Add("Green")
End Sub
End Class
Once you have a collection, you can bind the collection to an ItemsControl such as a ListBox. The following example shows how to create a collection to add to the list box by creating an ObjectDataProvider then bind it to the ListBox by using the ItemsSource property.
<Canvas.Resources>
<ObjectDataProvider x:Key="Colors" ObjectType="{x:Type src:myColors}"/>
</Canvas.Resources>
<ListBox Name="myListBox" HorizontalAlignment="Left" SelectionMode="Extended"
Width="265" Height="55" Background="HoneyDew"
ItemsSource="{Binding Source={StaticResource Colors}}" IsSynchronizedWithCurrentItem="true">
</ListBox>
For the complete sample see ListBox Sample.