如何:向 ItemsControl 添加数据

更新:2007 年 11 月

使用 ItemsControl 的可设置 ItemsSource 属性,您可以向 ItemsControl 添加数据。ItemsControl 中的项的类型为 ItemCollection。本示例演示如何创建添加到 ListBox 中的名为 Colors 的 ObservableCollection<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 示例