ITypedList Интерфейс

Определение

Предоставляет функциональные возможности для обнаружения схемы для привязываемого списка, где свойства, доступные для привязки, отличаются от общедоступных свойств объекта для привязки.

public interface class ITypedList
public interface ITypedList
type ITypedList = interface
Public Interface ITypedList
Производный

Примеры

В следующем примере кода показано, как реализовать интерфейс ITypedList. Универсальный тип, производный SortableBindingList от BindingList<T> класса и реализующий ITypedList интерфейс. Полный список кода см. в разделе "Практическое руководство. Реализация интерфейса ITypedList".

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace ITypedListCS;

[Serializable()]
public class SortableBindingList<T> : BindingList<T>, ITypedList
{
    [NonSerialized()]
    readonly PropertyDescriptorCollection properties;

    public SortableBindingList() : base()
    {
        // Get the 'shape' of the list. 
        // Only get the public properties marked with Browsable = true.
        PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(
            typeof(T),
            [new BrowsableAttribute(true)]);

        // Sort the properties.
        properties = pdc.Sort();
    }

    #region ITypedList Implementation

    public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        PropertyDescriptorCollection pdc;

        if (listAccessors != null && listAccessors.Length > 0)
        {
            // Return child list shape.
            pdc = ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType);
        }
        else
        {
            // Return properties in sort order.
            pdc = properties;
        }

        return pdc;
    }

    // This method is only used in the design-time framework 
    // and by the obsolete DataGrid control.
    public string GetListName(PropertyDescriptor[] listAccessors) => typeof(T).Name;

    #endregion
}
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Windows.Forms

<Serializable()> _
Public Class SortableBindingList(Of Tkey)
    Inherits BindingList(Of Tkey)
    Implements ITypedList

    <NonSerialized()> _
    Private properties As PropertyDescriptorCollection

    Public Sub New()
        MyBase.New()

        ' Get the 'shape' of the list. 
        ' Only get the public properties marked with Browsable = true.
        Dim pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(Tkey), New Attribute() {New BrowsableAttribute(True)})

        ' Sort the properties.
        properties = pdc.Sort()

    End Sub

#Region "ITypedList Implementation"

    Public Function GetItemProperties(ByVal listAccessors() As System.ComponentModel.PropertyDescriptor) As System.ComponentModel.PropertyDescriptorCollection Implements System.ComponentModel.ITypedList.GetItemProperties

        Dim pdc As PropertyDescriptorCollection

        If (Not (listAccessors Is Nothing)) And (listAccessors.Length > 0) Then
            ' Return child list shape
            pdc = ListBindingHelper.GetListItemProperties(listAccessors(0).PropertyType)
        Else
            ' Return properties in sort order
            pdc = properties
        End If

        Return pdc

    End Function

    ' This method is only used in the design-time framework 
    ' and by the obsolete DataGrid control.
    Public Function GetListName( _
    ByVal listAccessors() As PropertyDescriptor) As String _
    Implements System.ComponentModel.ITypedList.GetListName

        Return GetType(Tkey).Name

    End Function

#End Region

End Class

Комментарии

Используйте этот интерфейс, если, например, используется DataView объект, представляющий customer таблицу, необходимо привязать к свойствам customer объекта, DataView который представляет, а не свойствам DataView.

Этот интерфейс не требуется для поддержки привязываемого списка во время разработки.

Привязка к данным может происходить либо во время выполнения, либо в конструкторе, но существуют правила для обоих. Во время выполнения можно привязать к данным в любом из следующих элементов:

  • Array

  • Реализующий объект, предоставленный реализующим IList, имеет строго типизированное Item[] свойство (т. е. все, Type кроме Object). Это можно сделать, сделав реализацию по умолчанию частной Item[] . Если вы хотите создать объект IList , который следует правилам строго типизированной коллекции, следует наследовать от CollectionBase.

  • Реализация ITypedList.

В конструкторе можно инициализировать привязку к Component объектам, следуя тем же правилам.

Дополнительные сведения о привязке к источнику данных см. в System.Windows.Forms.Binding классе.

Методы

Имя Описание
GetItemProperties(PropertyDescriptor[])

PropertyDescriptorCollection Возвращает свойства для каждого элемента, используемого для привязки данных.

GetListName(PropertyDescriptor[])

Возвращает имя списка.

Применяется к

См. также раздел