方法 : ItemsControl にデータを追加する

ItemsControl には、ItemsControl にデータを追加できる、設定可能な ItemsSource プロパティがあります。ItemsControl 内の項目は ItemCollection 型です。ListBox に追加する Colors という名前の ObservableCollection を作成する方法を次の例に示します。

使用例

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

コレクションを作成したら、そのコレクションを ListBox などの ItemsControl にバインドできます。ObjectDataProvider を作成することによりリスト ボックスに追加するコレクションを作成し、そのコレクションを ItemsSource プロパティを使用して ListBox にバインドする方法を次の例に示します。

<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>

サンプル全体については、「ListBox のサンプル」を参照してください。