ITypedList Интерфейс

Определение

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

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

Примеры

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

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;

namespace ITypedListCS
{
    [Serializable()]
    public class SortableBindingList<T> : BindingList<T>, ITypedList
    {
        [NonSerialized()]
        private 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 Attribute[] { 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)
        {   
            return 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[])

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

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

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