AttributeTable - класс

Таблица атрибутов метаданных, используемых для определения внешнего вида и поведения во время разработки.

Иерархия наследования

System.Object
  Microsoft.Windows.Design.Metadata.AttributeTable

Пространство имен:  Microsoft.Windows.Design.Metadata
Сборка:  Microsoft.Windows.Design.Extensibility (в Microsoft.Windows.Design.Extensibility.dll)

Синтаксис

'Декларация
Public NotInheritable Class AttributeTable
public sealed class AttributeTable
public ref class AttributeTable sealed
[<Sealed>]
type AttributeTable =  class end
public final class AttributeTable

Тип AttributeTable предоставляет следующие члены.

Свойства

  Имя Описание
Открытое свойство AttributedTypes Получение перечисления всех типов, для которых существует переопределение атрибутов любого вида, например свойств или самого типа.

В начало страницы

Методы

  Имя Описание
Открытый метод ContainsAttributes Возврат значения, определяющего, содержит ли таблица метаданные для заданного типа.
Открытый метод Equals Определяет, равен ли заданный объект Object текущему объекту Object. (Унаследовано от Object.)
Защищенный метод Finalize Позволяет объекту попытаться освободить ресурсы и выполнить другие операции очистки, перед тем как объект будет утилизирован в процессе сборки мусора. (Унаследовано от Object.)
Открытый метод GetCustomAttributes(Assembly) Возврат перечисления всех атрибутов, предоставляемых для указанной сборки.
Открытый метод GetCustomAttributes(Type) Возврат перечисления всех атрибутов, предоставляемых для заданного типа.
Открытый метод GetCustomAttributes(Type, String) Возврат перечисления всех атрибутов, предоставляемых для заданного типа и имени члена.
Открытый метод GetHashCode Играет роль хэш-функции для определенного типа. (Унаследовано от Object.)
Открытый метод GetType Возвращает объект Type для текущего экземпляра. (Унаследовано от Object.)
Защищенный метод MemberwiseClone Создает неполную копию текущего объекта Object. (Унаследовано от Object.)
Открытый метод ToString Возвращение строки, представляющей текущий объект. (Унаследовано от Object.)

В начало страницы

Заметки

Класс AttributeTable предназначен для связывания атрибутов метаданных во время разработки с типами Windows Presentation Foundation (WPF).

Чтобы создать таблицу атрибутов, вызовите метод CreateTable класса AttributeTableBuilder. Дополнительные сведения см. в разделе Предоставление метаданных времени разработки.

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

Примеры

В следующем примере показано, как создать и заполнить таблицу атрибутов. Дополнительные сведения см. в разделе Пошаговое руководство. Создание графического элемента времени разработки.

Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Reflection
Imports System.Text
Imports System.Windows.Media
Imports System.Windows.Controls
Imports System.Windows

Imports Microsoft.Windows.Design
Imports Microsoft.Windows.Design.Features
Imports Microsoft.Windows.Design.Metadata

' The ProvideMetadata assembly-level attribute indicates to designers
' that this assembly contains a class that provides an attribute table. 
<Assembly: ProvideMetadata(GetType(CustomControlLibrary.VisualStudio.Design.Metadata))> 

' Container for any general design-time metadata to initialize.
' Designers look for a type in the design-time assembly that 
' implements IProvideAttributeTable. If found, designers instantiate
' this class and access its AttributeTable property automatically.
Friend Class Metadata
    Implements IProvideAttributeTable

    ' Accessed by the designer to register any design-time metadata.
    Public ReadOnly Property AttributeTable() As AttributeTable _
        Implements IProvideAttributeTable.AttributeTable
        Get
            Dim builder As New AttributeTableBuilder()

            ' Apply the ReadOnlyAttribute to the Background property 
            ' of the Button class.
            builder.AddCustomAttributes(GetType(Button), "Background", New ReadOnlyAttribute(True))

            Dim attributes As AttributeTable = builder.CreateTable()

            Dim hasCustomAttributes As Boolean = attributes.ContainsAttributes(GetType(Button))

            Dim types As IEnumerable(Of Type) = attributes.AttributedTypes

            ' The following code shows how to retrieve custom attributes
            ' using the GetCustomAttributes method overloads.
            Dim attrs0 As IEnumerable = attributes.GetCustomAttributes(GetType(Button))

            Dim attrs1 As IEnumerable = attributes.GetCustomAttributes(GetType(Button), "Background")

            Return attributes
        End Get
    End Property
End Class
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows;

using Microsoft.Windows.Design.Features;
using Microsoft.Windows.Design.Metadata;

// The ProvideMetadata assembly-level attribute indicates to designers
// that this assembly contains a class that provides an attribute table. 
[assembly: ProvideMetadata(typeof(CustomControlLibrary.VisualStudio.Design.Metadata))]
namespace CustomControlLibrary.VisualStudio.Design
{
    // Container for any general design-time metadata to initialize.
    // Designers look for a type in the design-time assembly that 
    // implements IProvideAttributeTable. If found, designers instantiate 
    // this class and access its AttributeTable property automatically.
    internal class Metadata : IProvideAttributeTable
    {
        // Accessed by the designer to register any design-time metadata.
        public AttributeTable AttributeTable
        {
            get
            {
                AttributeTableBuilder builder = new AttributeTableBuilder();

                // Apply the ReadOnlyAttribute to the Background property 
                // of the Button class.
                builder.AddCustomAttributes(
                    typeof(Button),
                    "Background",
                    new ReadOnlyAttribute(true));

                AttributeTable attributes = builder.CreateTable();

                bool hasCustomAttributes = attributes.ContainsAttributes(typeof(Button));

                IEnumerable<Type> types = attributes.AttributedTypes;

                // The following code shows how to retrieve custom attributes
                // using the GetCustomAttributes method overloads.
                IEnumerable attrs0 = attributes.GetCustomAttributes(typeof(Button));

                IEnumerable attrs1 = attributes.GetCustomAttributes(
                    typeof(Button),
                    "Background");

                return attributes;
            }
        }
    }
}

Потокобезопасность

Любые открытые члены этого типа, объявленные как static (Shared в Visual Basic), являются потокобезопасными. Потокобезопасность членов экземпляров не гарантируется.

См. также

Ссылки

Microsoft.Windows.Design.Metadata - пространство имен

AttributeTableBuilder

Другие ресурсы

Предоставление метаданных времени разработки