Поделиться через


AttributeTableBuilder - класс

Обновлен: Ноябрь 2007

Создание таблицы атрибутов, которая может быть передана в хранилище метаданных.

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

Синтаксис

'Декларация
Public Class AttributeTableBuilder
'Применение
Dim instance As AttributeTableBuilder
public class AttributeTableBuilder
public ref class AttributeTableBuilder
public class AttributeTableBuilder

Заметки

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

При добавлении большого числа атрибутов рекомендуется использовать класс AttributeCallbackBuilder вместо класса AttributeTableBuilder. Благодаря этому можно отложить создание атрибутов до того момента, когда конструктором будут запрошены метаданные для конечного типа.

Примеры

В следующем примере показано, как использовать класс 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.Features
Imports Microsoft.Windows.Design.Metadata

' Container for any general design-time metadata to initialize.
' Designers look for a type in the design-time assembly that 
' implements IRegisterMetadata. If found, designers instantiate 
' this class and call its Register() method automatically.
Friend Class Metadata
    Implements IRegisterMetadata

    ' Called by the designer to register any design-time metadata.
    Public Sub Register() Implements IRegisterMetadata.Register
        Dim builder As New AttributeTableBuilder()

        builder.AddCustomAttributes( _
            GetType(Button), _
            New DefaultPropertyAttribute("Content"))

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

        Dim properties As PropertyDescriptorCollection = _
            TypeDescriptor.GetProperties(GetType(Button))
        Dim pd As PropertyDescriptor = properties("Foreground")
        builder.AddCustomAttributes( _
            GetType(Button), _
            pd, _
            New ReadOnlyAttribute(True))

        builder.AddCustomAttributes( _
            GetType(Button), _
            Button.WidthProperty, _
            New ReadOnlyAttribute(True))

        Dim members As MemberInfo() = GetType(Button).GetMember("Height")
        builder.AddCustomAttributes( _
            GetType(Button), _
            members(0), _
            New ReadOnlyAttribute(True))

        Dim attributes As AttributeTable = builder.CreateTable()

        MetadataStore.AddAttributeTable(attributes)

    End Sub

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;

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 IRegisterMetadata. If found, designers instantiate 
    // this class and call its Register() method automatically.
    internal class Metadata : IRegisterMetadata
    {
        // Called by the designer to register any design-time metadata.
        public void Register()
        {
            AttributeTableBuilder builder = new AttributeTableBuilder();

            builder.AddCustomAttributes(
                typeof(Button),
                new DefaultPropertyAttribute("Content"));

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

            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(Button));
            PropertyDescriptor pd = properties["Foreground"];
            builder.AddCustomAttributes( 
                typeof(Button), 
                pd,
                new ReadOnlyAttribute(true)); 

            builder.AddCustomAttributes(
                typeof(Button),
                Button.WidthProperty,
                new ReadOnlyAttribute(true)); 

            MemberInfo[] members = typeof(Button).GetMember("Height");
            builder.AddCustomAttributes(
                typeof(Button),
                members[0],
                new ReadOnlyAttribute(true)); 

            AttributeTable attributes = builder.CreateTable();

            MetadataStore.AddAttributeTable(attributes);
        }
    }
}

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

System.Object
  Microsoft.Windows.Design.Metadata.AttributeTableBuilder

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

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

См. также

Ссылки

AttributeTableBuilder - члены

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

AttributeTable

AttributeCallbackBuilder

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

Хранилище метаданных