ControlBuilder 클래스

정의

컨트롤과 그 컨트롤에 포함되는 자식 컨트롤을 만들 때 페이지 파서를 지원합니다.

public ref class ControlBuilder
public class ControlBuilder
type ControlBuilder = class
Public Class ControlBuilder
상속
ControlBuilder
파생

예제

다음 코드 예제에서는 테이블이 빌드되는 시점에 특성과 콘텐츠가 정의된 컨트롤을 만듭니다 Table . 다음은 실행 파일을 빌드하는 데 사용할 명령줄입니다.

vbc /r:System.dll /r:System.Web.dll /r:System.Drawing.dll /t:library /out:myWebAppPath/Bin/vb_mycontrolbuilder.dll myControlBuilder.vb  
csc /t:library /out:myWebAppPath/Bin/cs_mycontrolbuilder.dll myControlBuilder.cs  
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Drawing;
using System.Security.Permissions;

namespace CustomControls
{
    [AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal)]
    public class MyTableCell : TableCell, INamingContainer { };

    [AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal)]
    public class MyCell
    /*
     * Class name: MyCell.
     * Declares the class for the child controls to include in the control collection.
     */
    {
        string _id;
        string _value;
        Color _backColor;

        public string CellID
        {
            get
            { return _id; }
            set
            { _id = value; }
        }

        public string Text
        {
            get
            { return _value; }
            set
            { _value = value; }
        }

        public Color BackColor
        {
            get
            { return _backColor; }
            set
            { _backColor = value; }
        }
    };

    [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
    public class MyControlBuilder : ControlBuilder
    {

        public override Type GetChildControlType(string tagName, IDictionary attribs)
        {
            // Allows TableRow without "runat=server" attribute to be added to the collection.
            if (String.Compare(tagName, "mycell", true) == 0)
                return typeof(MyCell);
            return null;
        }

        public override void AppendLiteralString(string s)
        {
            // Ignores literals between rows.
        }
    }
    [AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal)]
    [ControlBuilderAttribute(typeof(MyControlBuilder))]
    public class MyCS_CustomControl : Control, INamingContainer
    /*
     * Class name: MyCS_CustomControl.
     * Processes the element declarations within a control declaration. 
     * This builds the actual control.
     */
    {
        // Declares the custom control that must be built programmatically.
        Table _table;

        private String _title;
        private int _rows;
        private int _columns;

        Hashtable _cellObjects = new Hashtable();

        // Rows property to be used as the attribute name in the Web page.  
        public int Rows
        {
            get
            { return _rows; }
            set
            { _rows = value; }
        }

        // Columns property to be used as the attribute name in the Web page.
        public int Columns
        {
            get
            { return _columns; }
            set
            { _columns = value; }
        }

        // Title property to be used as the attribute name in the Web page.
        public string Title
        {
            get
            { return _title; }
            set
            { _title = value; }
        }

        protected void createNewRow(int rowNumber)
        {

            // Creates a row and adds it to the table.
            TableRow row;

            row = new TableRow();
            _table.Rows.Add(row);

            // Creates a cell that contains text.

            for (int y = 0; y < Columns; y++)
                appendCell(row, rowNumber, y);
        }

        protected void appendCell(TableRow row, int rowNumber, int cellNumber)
        {
            TableCell cell;
            TextBox textbox;

            cell = new TableCell();
            textbox = new TextBox();
            cell.Controls.Add(textbox);
            textbox.ID = "r" + rowNumber.ToString() + "c" + cellNumber.ToString();

            // Checks for the MyCell child object.
            if (_cellObjects[textbox.ID] != null)
            {
                MyCell cellLookup;
                cellLookup = (MyCell)_cellObjects[textbox.ID];

                textbox.Text = cellLookup.Text;
                textbox.BackColor = cellLookup.BackColor;
            }
            else
                textbox.Text = "Row: " + rowNumber.ToString() + " Cell: " +
                cellNumber.ToString();

            row.Cells.Add(cell);
        }

        // Called at runtime when a child object is added to the collection.  
        protected override void AddParsedSubObject(object obj)
        {
            MyCell cell = obj as MyCell;
            if (cell != null)
            {
                _cellObjects.Add(cell.CellID, cell);
            }
        }

        protected override void OnPreRender(EventArgs e)
        /*
         * Function name: OnPreRender.
         * Carries out changes affecting the control state and renders the resulting UI.
        */
        {

            // Increases the number of rows if needed.
            while (_table.Rows.Count < Rows)
            {
                createNewRow(_table.Rows.Count);
            }

            // Checks that each row has the correct number of columns.
            for (int i = 0; i < _table.Rows.Count; i++)
            {
                while (_table.Rows[i].Cells.Count < Columns)
                {
                    appendCell(_table.Rows[i], i, _table.Rows[i].Cells.Count);
                }

                while (_table.Rows[i].Cells.Count > Columns)
                {
                    _table.Rows[i].Cells.RemoveAt(_table.Rows[i].Cells.Count - 1);
                }
            }
        }

        protected override void CreateChildControls()
        /*
         * Function name: CreateChildControls.
         * Adds the Table and the text control to the control collection.
         */
        {
            LiteralControl text;

            // Initializes the text control using the Title property.
            text = new LiteralControl("<h5>" + Title + "</h5>");
            Controls.Add(text);

            _table = new Table();
            _table.BorderWidth = 2;
            Controls.Add(_table);
        }
    }
}
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections
Imports System.Drawing
Imports System.Security.Permissions


Namespace CustomControls

    <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
    Public Class MyTableCell
        Inherits TableCell
        Implements INamingContainer
    End Class


    <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
    Public Class MyCell
        Inherits Control
        Implements INamingContainer
        ' Class Name: MyCell.
        ' Declares the class for the child controls to be included in the control collection.

        Private _id As String
        Private _value As String
        Private _backColor As Color

        Public Property CellID() As String
            Get
                Return _id
            End Get
            Set(ByVal value As String)
                _id = value
            End Set
        End Property

        Public Property Text() As String
            Get
                Return _value
            End Get
            Set(ByVal value As String)
                _value = value
            End Set
        End Property


        Public Property BackColor() As Color
            Get
                Return _backColor
            End Get
            Set(ByVal value As Color)
                _backColor = value
            End Set
        End Property
    End Class

    <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
    Public Class MyControlBuilderVB
        Inherits ControlBuilder

        Public Overrides Function GetChildControlType(ByVal tagName As String, ByVal attribs As IDictionary) As Type

            ' Allows TableRow without "runat=server" attribute to be added to the collection.
            If (String.Compare(tagName, "mycell", True) = 0) Then
                Return GetType(MyCell)
            End If
            Return Nothing
        End Function

        ' Ignores literals between rows.
        Public Overrides Sub AppendLiteralString(ByVal s As String)
            ' Ignores literals between rows.
        End Sub

    End Class

    <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal), ControlBuilderAttribute(GetType(MyControlBuilderVB))> _
        Public Class MyVB_CustomControl
        Inherits Control
        Implements INamingContainer

        ' Class name: MyVB_CustomControl.
        ' Processes the element declarations within a control 
        ' declaration. This builds the actual control.

        ' Custom control to build programmatically.
        Private _table As Table

        Private _cellObjects As New Hashtable()

        ' Variables that must contain the control attributes as defined in the Web page.
        Private _rows As Integer
        Private _columns As Integer
        Private _title As String

        ' Rows property to be used as the attribute name in the Web page.     
        Public Property Rows() As Integer
            Get
                Return _rows
            End Get
            Set(ByVal value As Integer)
                _rows = value
            End Set
        End Property

        ' Columns property to be used as the attribute name in the Web page.

        Public Property Columns() As Integer
            Get
                Return _columns
            End Get
            Set(ByVal value As Integer)
                _columns = value
            End Set
        End Property

        ' Title property to be used as the attribute name in the Web page   
        Public Property Title() As String
            Get
                Return _title
            End Get
            Set(ByVal value As String)
                _title = value
            End Set
        End Property


        Protected Sub createNewRow(ByVal rowNumber As Integer)

            ' Creates a row and adds it to the table.
            Dim row As TableRow

            row = New TableRow()
            _table.Rows.Add(row)

            ' Creates a cell that contains text.
            Dim y As Integer
            For y = 0 To Columns - 1
                appendCell(row, rowNumber, y)
            Next y
        End Sub


        Protected Sub appendCell(ByVal row As TableRow, ByVal rowNumber As Integer, ByVal cellNumber As Integer)
            Dim cell As TableCell
            Dim textbox As TextBox

            cell = New TableCell()

            textbox = New TextBox()

            cell.Controls.Add(textbox)

            textbox.ID = "r" + rowNumber.ToString() + "c" + cellNumber.ToString()

            ' Checks for the MyCell child object.
            If Not (_cellObjects(textbox.ID) Is Nothing) Then
                Dim cellLookup As MyCell
                cellLookup = CType(_cellObjects(textbox.ID), MyCell)

                textbox.Text = cellLookup.Text
                textbox.BackColor = cellLookup.BackColor

            Else
                textbox.Text = "Row: " + rowNumber.ToString() + " Cell: " + cellNumber.ToString()
            End If

            row.Cells.Add(cell)
        End Sub

        ' Called at runtime when a child object is added to the collection.
        Protected Overrides Sub AddParsedSubObject(ByVal obj As Object)

            Dim cell As MyCell = CType(obj, MyCell)
            If Not (cell Is Nothing) Then
                _cellObjects.Add(cell.CellID, cell)
            End If
        End Sub


        Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
            ' Sub name: OnPreRender.
            ' Carries out changes affecting the control state and renders the resulting UI.

            ' Increases the number of rows if needed.
            While _table.Rows.Count < Rows
                createNewRow(_table.Rows.Count)
            End While

            ' Checks that each row has the correct number of columns.
            Dim i As Integer
            For i = 0 To _table.Rows.Count - 1
                While _table.Rows(i).Cells.Count < Columns
                    appendCell(_table.Rows(i), i, _table.Rows(i).Cells.Count)
                End While

                While _table.Rows(i).Cells.Count > Columns
                    _table.Rows(i).Cells.RemoveAt((_table.Rows(i).Cells.Count - 1))
                End While
            Next i
        End Sub


        <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name:="FullTrust")> _
        Protected Overrides Sub CreateChildControls()
            ' Sub name: CreateChildControls.
            ' Adds the Table and the text controls to the control collection. 


            Dim [text] As LiteralControl

            ' Initializes the text control using the Title property.
            [text] = New LiteralControl("<h5>" + Title + "</h5>")
            Controls.Add([text])


            _table = New Table()

            Controls.Add(_table)
        End Sub
    End Class

End Namespace

다음 코드 예제에서는 이전 사용자 지정 컨트롤을 사용 합니다. 특히 런타임에 특성과 콘텐츠가 정의된 테이블을 빌드합니다. @ Register 지시문에 표시된 값은 이전 명령줄을 반영합니다.

<%@ Page Language="C#" %>
<%@ Register TagPrefix="AspNetSamples" Assembly="cs_mycontrolbuilder" Namespace="CustomControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ControlBuilder Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <AspNetSamples:MyCS_CustomControl id="Custom1" 
                                         title="Auto-Generated Table"
                                         columns="3"
                                         rows="3"  
                                         runat="server">
         <mycell cellid="r0c0" BackColor="red" text="red cell"></mycell>
         <mycell cellid="r2c2" BackColor="green" text="green cell"></mycell>
       </AspNetSamples:MyCS_CustomControl>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register TagPrefix="AspNetSamples" Assembly="vb_mycontrolbuilder" Namespace="CustomControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ControlBuilder Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <AspNetSamples:MyVB_CustomControl id="Custom1" 
                                         title="Auto-Generated Table"
                                         columns="3"
                                         rows="3"  
                                         runat="server">
         <mycell cellid="r0c0" BackColor="red" text="red cell"></mycell>
         <mycell cellid="r2c2" BackColor="green" text="green cell"></mycell>
       </AspNetSamples:MyVB_CustomControl>
    </div>
    </form>
</body>
</html>

설명

기본적으로 페이지의 모든 컨트롤은 기본 ControlBuilder 클래스와 연결됩니다. 구문 분석하는 동안 ASP.NET 페이지 프레임워크는 페이지의 컨트롤 트리 ControlBuilder 에 해당하는 개체 트리를 빌드합니다. 그런 다음 트리를 ControlBuilder 사용하여 컨트롤 트리를 만드는 페이지 코드를 생성합니다. 자식 컨트롤 외에도 는 ControlBuilder 컨트롤 태그 내의 콘텐츠를 구문 분석하는 방법의 동작을 정의합니다. 사용자 고유의 사용자 지정 컨트롤 작성기 클래스를 정의하여 이 기본 동작을 재정의할 수 있습니다. 이 작업은 다음과 같이 컨트롤 작성기 클래스에 특성을 적용하여 ControlBuilderAttribute 수행됩니다.

[ControlBuilderAttribute(typeof(ControlBuilderType))]

생성자

ControlBuilder()

ControlBuilder 클래스의 새 인스턴스를 초기화합니다.

필드

DesignerFilter

리터럴 문자열을 "__designer" 나타냅니다.

속성

BindingContainerBuilder

이 빌더가 만드는 컨트롤의 바인딩 컨테이너에 해당하는 컨트롤 작성기를 가져옵니다.

BindingContainerType

이 작성기가 만드는 컨트롤의 바인딩 컨테이너 형식을 가져옵니다.

ComplexPropertyEntries

복합 속성 항목의 컬렉션을 가져옵니다.

ControlType

만들려는 컨트롤의 Type을 가져옵니다.

CurrentFilterResolutionService

디자이너에서 컨트롤을 구문 분석하고 유지할 때 디바이스 필터 관련 서비스를 관리하는 데 사용되는 IFilterResolutionService 개체입니다.

DeclareType

코드 생성에서 컨트롤을 선언하는 데 사용되는 형식을 가져옵니다.

FChildrenAsProperties

컨트롤에 ParseChildrenAttributetrue로 설정된 ChildrenAsProperties가 있는지 여부를 나타내는 값을 가져옵니다.

FIsNonParserAccessor

컨트롤이 IParserAccessor 인터페이스를 구현하는지 여부를 결정하는 값을 가져옵니다.

HasAspCode

컨트롤에 코드 블록이 포함되어 있는지 여부를 나타내는 값을 가져옵니다.

ID

만들려는 컨트롤의 ID 속성을 가져오거나 설정합니다.

InDesigner

ControlBuilder가 디자이너에서 실행되고 있는지 여부를 반환합니다.

InPageTheme

ControlBuilder 개체가 페이지 테마를 생성하는 데 사용할지 여부를 결정하는 부울 값을 가져옵니다.

ItemType

바인딩 컨테이너에 설정된 형식을 가져옵니다.

Localize

ControlBuilder 개체에서 만든 컨트롤이 지역화되어 있는지 여부를 나타내는 부울 값을 가져옵니다.

NamingContainerType

이 작성기에서 만든 컨트롤의 명명 컨테이너 형식을 가져옵니다.

PageVirtualPath

ControlBuilder 인스턴스로 빌드할 페이지의 가상 경로를 가져옵니다.

Parser

컨트롤을 구문 분석하는 TemplateParser를 가져옵니다.

ServiceProvider

ControlBuilder 개체의 서비스 개체를 가져옵니다.

SubBuilders

ControlBuilder 개체에 대한 하위 ControlBuilder 개체의 목록을 가져옵니다.

TagName

만들려는 컨트롤의 태그 이름을 가져옵니다.

TemplatePropertyEntries

템플릿 속성 항목의 컬렉션을 가져옵니다.

ThemeResolutionService

디자인 타임에 컨트롤 테마와 스킨을 관리하는 데 사용되는 IThemeResolutionService 개체를 가져옵니다.

메서드

AllowWhitespaceLiterals()

콘텐츠에서 컨트롤의 여는 태그와 닫는 태그 사이에 공백 리터럴이 허용되는지 여부를 결정합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

AppendLiteralString(String)

지정된 리터럴 콘텐츠를 컨트롤에 추가합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

AppendSubBuilder(ControlBuilder)

컨테이너 컨트롤에 속하는 모든 자식 컨트롤에 대한 ControlBuilder 개체에 빌더를 추가합니다.

BuildObject()

ControlBuilder 개체가 참조하는 컨트롤의 디자인 타임 인스턴스를 빌드합니다.

CloseControl()

파서에서 호출하여 컨트롤의 여는 태그와 닫는 태그의 구문 분석이 완료되었음을 작성기에 알려 줍니다.

CreateBuilderFromType(TemplateParser, ControlBuilder, Type, String, String, IDictionary, Int32, String)

지정한 태그 이름과 개체 형식은 물론 작성기를 정의하는 다른 매개 변수에서 ControlBuilder 개체를 만듭니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetChildControlType(String, IDictionary)

자식 태그에 해당하는 컨트롤 형식의 Type을 가져옵니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectPersistData()

ObjectPersistData 개체의 ControlBuilder 개체를 만듭니다.

GetResourceKey()

ControlBuilder 개체의 리소스 키를 검색합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
HasBody()

컨트롤에 여는 태그와 닫는 태그가 있는지 여부를 결정합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

HtmlDecodeLiterals()

HTML 컨트롤의 리터럴 문자열이 HTML로 디코딩되는지 여부를 결정합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

Init(TemplateParser, ControlBuilder, Type, String, String, IDictionary)

인스턴스화된 후에 사용하기 위해 ControlBuilder를 초기화합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
NeedsTagInnerText()

컨트롤 작성기가 내부 텍스트를 가져오는지 결정합니다. 내부 텍스트를 가져오려면 SetTagInnerText(String) 메서드가 호출되어야 합니다. 이 메서드는 ASP.NET 페이지 프레임워크에서 호출합니다.

OnAppendToParentBuilder(ControlBuilder)

내부 텍스트가 부모 컨트롤 작성기에 추가되고 있음을 ControlBuilder에 알립니다.

ProcessGeneratedCode(CodeCompileUnit, CodeTypeDeclaration, CodeTypeDeclaration, CodeMemberMethod, CodeMemberMethod)

사용자 지정 컨트롤 작성기를 활성화하여 생성된 CodeDom(코드 문서 개체 모델)에 액세스하고, 컨트롤을 구문 분석 및 작성하는 동안 코드를 삽입 및 수정합니다.

SetResourceKey(String)

ControlBuilder 개체의 리소스 키를 설정합니다.

SetServiceProvider(IServiceProvider)

ControlBuilder 개체의 서비스 개체를 설정합니다.

SetTagInnerText(String)

컨트롤 태그의 내부 텍스트를 ControlBuilder에 제공합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보