HOW TO:建立和繫結至 ObservableCollection
這個範例顯示如何建立和繫結至衍生自 ObservableCollection<T> 類別的集合,這個集合類別會在加入或移除項目時提供告知。
範例
下列範例顯示 NameList 集合的實作:
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
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; }
}
}
您可以使用讓其他 common language runtime (CLR) 物件變為可用的相同方式,將集合變為可用來進行繫結 (如 HOW TO:讓資料可於 XAML 中繫結中所述)。 例如,您可以使用 XAML 具現化 (Instantiate) 集合,並將集合指定為資源 (如這裡所示):
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://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 的定義。
注意事項 |
---|
集合中的物件必須滿足繫結來源概觀中所述的需求。尤其是如果使用 OneWay 或 TwoWay (例如,想要在來源屬性動態變更時更新 UI),則必須實作適合的屬性變更告知機制 (如 INotifyPropertyChanged 介面)。 |
如需詳細資訊,請參閱資料繫結概觀中的<繫結至集合>一節。