共用方式為


HOW TO:將資料加入 ItemsControl

更新:2007 年 11 月

ItemsControl 具有可設定的 ItemsSource 屬性,讓您可以將資料加入至 ItemsControlItemsControl 中的項目是 ItemCollection 型別。這個範例示範如何建立名為 Colors 且加入至 ListBoxObservableCollection<T>

範例

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
public class myColors : ObservableCollection<string>
{
    public myColors()
    {
        Add("LightBlue");
        Add("Pink");
        Add("Red");
        Add("Purple");
        Add("Blue");
        Add("Green");
    }
}

具有集合後,可以將集合繫結至 ItemsControl,例如 ListBox。下列範例顯示如何藉由下列方法建立集合並將它加入至清單方塊:建立 ObjectDataProvider,然後使用 ItemsSource 屬性將它繫結至 ListBox

<Canvas.Resources>
  <src:myColors x:Key="Colors"/>
</Canvas.Resources>
<ListBox Name="myListBox" HorizontalAlignment="Left" SelectionMode="Extended" 
      Width="265" Height="55" Background="HoneyDew" SelectionChanged="myListBox_SelectionChanged"
      ItemsSource="{Binding Source={StaticResource Colors}}" IsSynchronizedWithCurrentItem="true">
</ListBox>

如需完整範例,請參閱 ListBox 範例