如何创建并绑定到 ObservableCollection

此示例演示如何创建和绑定到派生自类的 ObservableCollection<T> 集合,该集合类是在添加或删除项时提供通知的集合类。

示例:

以下示例展示了 NameList 集合的实现:

public class NameList : ObservableCollection<PersonName>
{
    public NameList() : base()
    {
        Add(new PersonName("Willa", "Cather"));
        Add(new PersonName("Isak", "Dinesen"));
        Add(new PersonName("Victor", "Hugo"));
        Add(new PersonName("Jules", "Verne"));
    }
  }

  public class PersonName
  {
      private string firstName;
      private string lastName;

      public PersonName(string first, string last)
      {
          this.firstName = first;
          this.lastName = last;
      }

      public string FirstName
      {
          get { return firstName; }
          set { firstName = value; }
      }

      public string LastName
      {
          get { return lastName; }
          set { lastName = value; }
      }
  }
Public Class NameList
    Inherits ObservableCollection(Of PersonName)

    ' Methods
    Public Sub New()
        MyBase.Add(New PersonName("Willa", "Cather"))
        MyBase.Add(New PersonName("Isak", "Dinesen"))
        MyBase.Add(New PersonName("Victor", "Hugo"))
        MyBase.Add(New PersonName("Jules", "Verne"))
    End Sub

End Class

Public Class PersonName
    ' Methods
    Public Sub New(ByVal first As String, ByVal last As String)
        Me._firstName = first
        Me._lastName = last
    End Sub

    ' Properties
    Public Property FirstName() As String
        Get
            Return Me._firstName
        End Get
        Set(ByVal value As String)
            Me._firstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return Me._lastName
        End Get
        Set(ByVal value As String)
            Me._lastName = value
        End Set
    End Property

    ' Fields
    Private _firstName As String
    Private _lastName As String
End Class

可以像使用其他公共语言运行时 (CLR) 对象一样,使集合可用于绑定,如 XAML 中的“使数据可供绑定”中所述。 例如,可以在 XAML 中实例化集合并将集合指定为资源,如下所示:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:SDKSample"
  x:Class="SDKSample.Window1"
  Width="400"
  Height="280"
  Title="MultiBinding Sample">

  <Window.Resources>
    <c:NameList x:Key="NameListData"/>

...

</Window.Resources>

您就可以绑定到集合:

<ListBox Width="200"
         ItemsSource="{Binding Source={StaticResource NameListData}}"
         ItemTemplate="{StaticResource NameItemTemplate}"
         IsSynchronizedWithCurrentItem="True"/>

此处未显示定义 NameItemTemplate

注释

集合中的对象必须满足 绑定源概述中所述的要求。 特别是,如果使用 OneWayTwoWay (例如,希望 UI 在源属性动态更改时更新),则必须实现适当的属性更改通知机制,例如 INotifyPropertyChanged 接口。

有关详细信息,请参阅 数据绑定概述中的“绑定到集合”部分。

另请参阅