Condividi tramite


Procedura: Creare e associare a un oggetto ObservableCollection

In questo esempio viene illustrato come creare e associare a una raccolta che deriva dalla classe ObservableCollection<T>, ovvero una classe di raccolta che fornisce notifiche quando gli elementi vengono aggiunti o rimossi.

Esempio

L'esempio seguente illustra l'implementazione di una collezione 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

Puoi rendere disponibile la raccolta per l'associazione allo stesso modo con altri oggetti CLR (Common Language Runtime), come descritto in Rendi i dati disponibili per l'associazione in XAML. Ad esempio, puoi creare un'istanza della raccolta in XAML e fare riferimento alla raccolta come risorsa, come illustrato di seguito.

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

È quindi possibile associare alla raccolta:

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

La definizione di NameItemTemplate non è illustrata qui.

Annotazioni

Gli oggetti nella raccolta devono soddisfare i requisiti descritti nella panoramica delle origini di associazione . In particolare, se usi OneWay o TwoWay (ad esempio, vuoi che l'interfaccia utente venga aggiornata quando le proprietà di origine cambiano dinamicamente), devi implementare un meccanismo di notifica di modifica della proprietà appropriato, ad esempio l'interfaccia di INotifyPropertyChanged.

Per altre informazioni, vedere la sezione Binding to Collections in Data Binding Overview.

Vedere anche