ControlBuilder Kelas

Definisi

Mendukung pengurai halaman dalam membangun kontrol dan kontrol anak yang dikandungnya.

public ref class ControlBuilder
public class ControlBuilder
type ControlBuilder = class
Public Class ControlBuilder
Warisan
ControlBuilder
Turunan

Contoh

Contoh kode berikut membuat kontrol yang Table atribut dan kontennya ditentukan pada saat tabel dibuat. Berikut ini adalah baris perintah yang akan digunakan untuk membangun executable.

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

Contoh kode berikut menggunakan kontrol kustom sebelumnya. Secara khusus, ini membangun tabel yang atribut dan kontennya didefinisikan pada durasi. Perhatikan bahwa nilai yang ditampilkan di direktif @ Register mencerminkan baris perintah sebelumnya.

<%@ 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>

Keterangan

Secara default, setiap kontrol pada halaman dikaitkan dengan kelas default ControlBuilder . Selama penguraian, kerangka kerja halaman ASP.NET membangun pohon ControlBuilder objek yang sesuai dengan pohon kontrol untuk halaman. Pohon ControlBuilder kemudian digunakan untuk menghasilkan kode halaman untuk membuat pohon kontrol. Selain kontrol anak, ControlBuilder menentukan perilaku bagaimana konten dalam tag kontrol diurai. Anda dapat mengambil alih perilaku default ini dengan mendefinisikan kelas penyusun kontrol kustom Anda sendiri. Ini dilakukan dengan menerapkan ControlBuilderAttribute atribut ke kelas penyusun kontrol Anda sebagai berikut:

[ControlBuilderAttribute(typeof(ControlBuilderType))]

Konstruktor

ControlBuilder()

Menginisialisasi instans baru kelas ControlBuilder.

Bidang

DesignerFilter

"__designer" Mewakili string harfiah.

Properti

BindingContainerBuilder

Mendapatkan penyusun kontrol yang sesuai dengan kontainer pengikatan untuk kontrol yang dibuat penyusun ini.

BindingContainerType

Mendapatkan jenis kontainer pengikatan untuk kontrol yang dibuat penyusun ini.

ComplexPropertyEntries

Mendapatkan kumpulan entri properti yang kompleks.

ControlType

Type Mendapatkan untuk kontrol yang akan dibuat.

CurrentFilterResolutionService

IFilterResolutionService Mendapatkan objek yang digunakan untuk mengelola layanan terkait filter perangkat saat mengurai dan mempertahankan kontrol dalam perancang.

DeclareType

Mendapatkan jenis yang akan digunakan oleh pembuatan kode untuk mendeklarasikan kontrol.

FChildrenAsProperties

Mendapatkan nilai yang menentukan apakah kontrol memiliki dengan ChildrenAsProperties diatur ParseChildrenAttribute ke true.

FIsNonParserAccessor

Mendapatkan nilai yang menentukan apakah kontrol mengimplementasikan IParserAccessor antarmuka.

HasAspCode

Mendapatkan nilai yang menunjukkan apakah kontrol berisi blok kode apa pun.

ID

Mendapatkan atau mengatur properti pengidentifikasi untuk kontrol yang akan dibangun.

InDesigner

Mengembalikan apakah ControlBuilder berjalan di perancang.

InPageTheme

Mendapatkan nilai Boolean yang menunjukkan apakah objek ini ControlBuilder digunakan untuk menghasilkan tema halaman.

ItemType

Mendapatkan jenis yang diatur pada kontainer pengikatan.

Localize

Mendapatkan nilai Boolean yang menunjukkan apakah kontrol yang dibuat oleh objek ini ControlBuilder dilokalkan.

NamingContainerType

Mendapatkan jenis kontainer penamaan untuk kontrol yang dibuat penyusun ini.

PageVirtualPath

Mendapatkan jalur virtual halaman yang akan dibangun oleh instans ini ControlBuilder .

Parser

Mendapatkan yang TemplateParser bertanggung jawab untuk mengurai kontrol.

ServiceProvider

Mendapatkan objek layanan untuk objek ini ControlBuilder .

SubBuilders

Mendapatkan daftar objek anak ControlBuilder untuk obyek ini ControlBuilder .

TagName

Mendapatkan nama tag untuk kontrol yang akan dibangun.

TemplatePropertyEntries

Mendapatkan kumpulan entri properti templat.

ThemeResolutionService

IThemeResolutionService Mendapatkan objek yang digunakan dalam waktu desain untuk mengelola tema kontrol dan kulit.

Metode

AllowWhitespaceLiterals()

Menentukan apakah literal spasi kosong diizinkan dalam konten antara tag pembuka dan penutup kontrol. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

AppendLiteralString(String)

Menambahkan konten harfiah yang ditentukan ke kontrol. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

AppendSubBuilder(ControlBuilder)

Menambahkan penyusun ke ControlBuilder objek untuk setiap kontrol anak yang termasuk dalam kontrol kontainer.

BuildObject()

Membangun instans waktu desain kontrol yang dirujuk oleh objek ini ControlBuilder .

CloseControl()

Dipanggil oleh pengurai untuk memberi tahu penyusun bahwa penguraian tag pembuka dan penutup kontrol selesai.

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

ControlBuilder Membuat objek dari nama tag dan jenis objek yang ditentukan, serta parameter lain yang menentukan penyusun.

Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
GetChildControlType(String, IDictionary)

Type Mendapatkan jenis kontrol yang sesuai dengan tag anak. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetObjectPersistData()

ObjectPersistData Membuat objek untuk obyek iniControlBuilder.

GetResourceKey()

Mengambil kunci sumber daya untuk objek ini ControlBuilder .

GetType()

Mendapatkan dari instans Type saat ini.

(Diperoleh dari Object)
HasBody()

Menentukan apakah kontrol memiliki tag pembuka dan penutup. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

HtmlDecodeLiterals()

Menentukan apakah string literal kontrol HTML harus didekodekan HTML. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

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

Menginisialisasi ControlBuilder untuk digunakan setelah instans. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

MemberwiseClone()

Membuat salinan dangkal dari saat ini Object.

(Diperoleh dari Object)
NeedsTagInnerText()

Menentukan apakah penyusun kontrol perlu mendapatkan teks dalamnya. Jika demikian, SetTagInnerText(String) metode harus dipanggil. Metode ini dipanggil oleh kerangka kerja halaman ASP.NET.

OnAppendToParentBuilder(ControlBuilder)

Memberi tahu ControlBuilder bahwa itu sedang ditambahkan ke penyusun kontrol induk.

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

Memungkinkan penyusun kontrol kustom untuk mengakses Code Document Object Model (CodeDom) yang dihasilkan dan menyisipkan dan memodifikasi kode selama proses penguraian dan kontrol bangunan.

SetResourceKey(String)

Menyetel kunci sumber daya untuk objek ini ControlBuilder .

SetServiceProvider(IServiceProvider)

Menyetel objek layanan untuk objek ini ControlBuilder .

SetTagInnerText(String)

ControlBuilder Menyediakan teks dalam tag kontrol.

ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)

Berlaku untuk

Lihat juga