Ler en inglés

Compartir por


EditableDesignerRegion Clase

Definición

Representa un área modificable de contenido en el marcado en tiempo de diseño para el control asociado.

C#
public class EditableDesignerRegion : System.Web.UI.Design.DesignerRegion
Herencia
EditableDesignerRegion
Derivado

Ejemplos

En este ejemplo se muestra cómo crear un control con dos regiones en las que se pueden hacer clic y un EditableDesignerRegion objeto con dos vistas o plantillas. Compile el proyecto y abra la página en un diseñador visual y cambie a la vista de diseño (WYSIWYG). Hay dos vistas en las que se puede hacer clic, View1 y View2. Haga clic en Ver1 y arrastre el CheckBox control desde la parte inferior de la página a la región del diseñador vacía justo debajo de las regiones en las que se puede hacer clic. Haga clic en Ver2 y arrastre el RadioButton control a la región del diseñador vacía. Vuelva a hacer clic en Ver1 y vuelva a aparecer la región con las CheckBox repeticiones. Haga clic en Ver2 y en la región con las RadioButton repeticiones. Vuelva a la vista de origen para ver cómo se conservan los cambios en el marcado HTML.

Nota

El proyecto debe tener una referencia al ensamblado System.Design.dll.

C#
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;
using System.Web.UI.WebControls;

namespace Samples.ASPNet.ControlDesigners_CS 
{
    [
        Designer(typeof(MyMultiRegionControlDesigner)), 
        ToolboxData("<{0}:MyMultiRegionControl runat=\"server\" width=\"200\"></{0}:MyMultiRegionControl>")
    ]
    public class MyMultiRegionControl : CompositeControl
    {
        // Define the templates that represent 2 views on the control
        private ITemplate _view1;
        private ITemplate _view2;

        // Create persistable inner properties 
        // for the two editable views
        [PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(null)]
        public virtual ITemplate View1
        {
            get { return _view1; }
            set { _view1 = value; }
        }
        [PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(null)]
        public virtual ITemplate View2
        {
            get { return _view2; }
            set { _view2 = value; }
        }

        // The current view on the control; 0 = view1, 1 = view2
        private int _currentView = 0;
        public int CurrentView
        {
            get { return _currentView; }
            set { _currentView = value; }
        }

        // Create a simple table with a row of two clickable, 
        // readonly headers and a row with a single column, which 
        // is the 'container' to which we'll be adding controls.
        protected override void CreateChildControls()
        {
            // Always start with a clean form
            Controls.Clear();

            // Create a table using the control's declarative properties
            Table t = new Table();
            t.CellSpacing = 1;
            t.BorderStyle = BorderStyle;
            t.Width = this.Width;
            t.Height = this.Height;

            // Create the header row
            TableRow tr = new TableRow();
            tr.HorizontalAlign = HorizontalAlign.Center;
            tr.BackColor = Color.LightBlue;

            // Create the first cell in the header row
            TableCell tc = new TableCell();
            tc.Text = "View 1";
            tc.Width = new Unit("50%");
            tr.Cells.Add(tc);

            // Create the second cell in the header row
            tc = new TableCell();
            tc.Text = "View 2";
            tc.Width = new Unit("50%");
            tr.Cells.Add(tc);

            t.Rows.Add(tr);

            // Create the second row for content
            tr = new TableRow();
            tr.HorizontalAlign = HorizontalAlign.Center;

            // This cell represents our content 'container'
            tc = new TableCell();
            tc.ColumnSpan = 2;

            // Add the current view content to the cell
            // at run-time
            if (!DesignMode)
            {
                Control containerControl = new Control();
                switch (CurrentView)
                {
                    case 0:
                        if (View1 != null)
                            View1.InstantiateIn(containerControl);
                        break;
                    case 1:
                        if (View2 != null)
                            View2.InstantiateIn(containerControl);
                        break;
                }

                tc.Controls.Add(containerControl);
            }

            tr.Cells.Add(tc);

            t.Rows.Add(tr);

            // Add the finished table to the Controls collection
            Controls.Add(t);
        }
    }

    //---------------------------------------------------------
    // Region-based control designer for the above web control, 
    // derived from CompositeControlDesigner.
    public class MyMultiRegionControlDesigner : CompositeControlDesigner 
    {
        private MyMultiRegionControl myControl;

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);
            myControl = (MyMultiRegionControl)component;
        }

        // Make this control resizeable on the design surface
        public override bool AllowResize
        {
            get
            {
                return true;
            }
        }

        // Use the base to create child controls, then add region markers
        protected override void CreateChildControls() {
            base.CreateChildControls();

            // Get a reference to the table, which is the first child control
            Table t = (Table)myControl.Controls[0];

            // Add design time markers for each of the three regions
            if (t != null)
            {
                // View1
                t.Rows[0].Cells[0].Attributes[DesignerRegion.DesignerRegionAttributeName] = "0";
                // View2
                t.Rows[0].Cells[1].Attributes[DesignerRegion.DesignerRegionAttributeName] = "1";
                // Editable region
                t.Rows[1].Cells[0].Attributes[DesignerRegion.DesignerRegionAttributeName] = "2";
            }
        }

        // Handler for the Click event, which provides the region in the arguments.
        protected override void OnClick(DesignerRegionMouseEventArgs e)
        {
            if (e.Region == null)
                return;

            // If the clicked region is not a header, return
            if (e.Region.Name.IndexOf("Header") != 0)
                return;

            // Switch the current view if required
            if (e.Region.Name.Substring(6, 1) != myControl.CurrentView.ToString())
            {
                myControl.CurrentView = int.Parse(e.Region.Name.Substring(6, 1));
                base.UpdateDesignTimeHtml();
            }
        }

        // Create the regions and design-time markup. Called by the designer host.
        public override String GetDesignTimeHtml(DesignerRegionCollection regions) {
            // Create 3 regions: 2 clickable headers and an editable row
            regions.Add(new DesignerRegion(this, "Header0"));
            regions.Add(new DesignerRegion(this, "Header1"));

            // Create an editable region and add it to the regions
            EditableDesignerRegion editableRegion = 
                new EditableDesignerRegion(this, 
                    "Content" + myControl.CurrentView, false);
            regions.Add(editableRegion);

            // Set the highlight for the selected region
            regions[myControl.CurrentView].Highlight = true;

            // Use the base class to render the markup
            return base.GetDesignTimeHtml();
        }

        // Get the content string for the selected region. Called by the designer host?
        public override string GetEditableDesignerRegionContent(EditableDesignerRegion region) 
        {
            // Get a reference to the designer host
            IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost));
            if (host != null)
            {
                ITemplate template = myControl.View1;
                if (region.Name == "Content1")
                    template = myControl.View2;

                // Persist the template in the design host
                if (template != null)
                    return ControlPersister.PersistTemplate(template, host);
            }

            return String.Empty;
        }

        // Create a template from the content string and  
        // put it in the selected view.
        public override void SetEditableDesignerRegionContent(EditableDesignerRegion region, string content)
        {
            if (content == null)
                return;

            // Get a reference to the designer host
            IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost));
            if (host != null)
            {
                // Create a template from the content string
                ITemplate template = ControlParser.ParseTemplate(host, content);

                // Determine which region should get the template
                // Either 'Content0' or 'Content1'
                if (region.Name.EndsWith("0"))
                    myControl.View1 = template;
                else if (region.Name.EndsWith("1"))
                    myControl.View2 = template;
            }
        }
    }
}
ASP.NET (C#)
<%@ Page Language="C#"  %>
<%@ Register TagPrefix="aspSample" 
    Assembly="Samples.ASPNet.ControlDesigners_CS" 
    Namespace="Samples.ASPNet.ControlDesigners_CS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Designers Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <aspSample:MyMultiRegionControl ID="myCtl" Runat=Server Width=200 Height=75 BorderStyle=solid >
        </aspSample:MyMultiRegionControl><br />
        <asp:CheckBox ID="CheckBox1" runat="server" />
        <asp:RadioButton ID="RadioButton1" runat="server" />

    </div>
    </form>
</body>
</html>

Comentarios

Use la EditableDesignerRegion clase para ayudar a administrar plantillas en tiempo de diseño. Un ControlDesigner usará una instancia de esta clase con su GetEditableDesignerRegionContent método para generar marcado HTML del contenido de la región.

Constructores

EditableDesignerRegion(ControlDesigner, String)

Inicializa una nueva instancia de la clase EditableDesignerRegion con el nombre y el propietario proporcionados.

EditableDesignerRegion(ControlDesigner, String, Boolean)

Crea una nueva instancia de la clase EditableDesignerRegion utilizando el nombre y el propietario proporcionados y el valor inicial de la propiedad ServerControlsOnly.

Propiedades

Content

Obtiene o establece el formato HTML para el contenido del área.

Description

Obtiene o establece la descripción de una región del diseñador.

(Heredado de DesignerRegion)
Designer

Obtiene el componente del diseñador asociado.

(Heredado de DesignerObject)
DisplayName

Obtiene o establece el nombre descriptivo que se va a mostrar de una región del diseñador.

(Heredado de DesignerRegion)
EnsureSize

Obtiene o establece un valor que indica si el host del diseñador va a establecer explícitamente el tamaño de la región del diseñador.

(Heredado de DesignerRegion)
Highlight

Obtiene o establece un valor que indica si la región del diseñador se va a resaltar en la superficie de diseño.

(Heredado de DesignerRegion)
Name

Obtiene el nombre del objeto.

(Heredado de DesignerObject)
Properties

Obtiene las propiedades del objeto.

(Heredado de DesignerObject)
Selectable

Obtiene o establece un valor que indica si el usuario puede seleccionar la región del diseñador en la superficie de diseño.

(Heredado de DesignerRegion)
Selected

Obtiene o establece un valor que indica si la región del diseñador está actualmente seleccionada en la superficie de diseño.

(Heredado de DesignerRegion)
ServerControlsOnly

Obtiene o establece un valor que indica si el área sólo acepta controles de servidor Web.

SupportsDataBinding

Obtiene o establece un valor que indica si el área se puede enlazar a un origen de datos.

UserData

Obtiene o establece datos de usuario opcionales que se van a asociar a la región del diseñador.

(Heredado de DesignerRegion)

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetBounds()

Recupera el tamaño de la región del diseñador en la superficie de diseño.

(Heredado de DesignerRegion)
GetChildViewRendering(Control)

Devuelve un objeto ViewRendering que contiene el formato HTML en tiempo de diseño para el control proporcionado.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetService(Type)

Obtiene un servicio del host de diseño identificado por el tipo proporcionado.

(Heredado de DesignerObject)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

IServiceProvider.GetService(Type)

Para obtener una descripción de este miembro, vea GetService(Type).

(Heredado de DesignerObject)

Métodos de extensión

GetKeyedService<T>(IServiceProvider, Object)

Obtiene un servicio de tipo T de .IServiceProvider

GetKeyedServices(IServiceProvider, Type, Object)

Obtiene una enumeración de servicios de tipo serviceType de .IServiceProvider

GetKeyedServices<T>(IServiceProvider, Object)

Obtiene una enumeración de servicios de tipo T de .IServiceProvider

GetRequiredKeyedService(IServiceProvider, Type, Object)

Obtiene un servicio de tipo serviceType de .IServiceProvider

GetRequiredKeyedService<T>(IServiceProvider, Object)

Obtiene un servicio de tipo T de .IServiceProvider

CreateAsyncScope(IServiceProvider)

Crea una instancia de AsyncServiceScope que se puede usar para resolver los servicios con ámbito.

CreateScope(IServiceProvider)

Crea una instancia de IServiceScope que se puede usar para resolver los servicios con ámbito.

GetRequiredService(IServiceProvider, Type)

Obtiene el servicio de tipo serviceType de IServiceProvider.

GetRequiredService<T>(IServiceProvider)

Obtiene el servicio de tipo T de IServiceProvider.

GetService<T>(IServiceProvider)

Obtiene el servicio de tipo T de IServiceProvider.

GetServices(IServiceProvider, Type)

Obtiene una enumeración de los servicios de tipo serviceType de IServiceProvider.

GetServices<T>(IServiceProvider)

Obtiene una enumeración de los servicios de tipo T de IServiceProvider.

GetFakeLogCollector(IServiceProvider)

Obtiene el objeto que recopila los registros enviados al registrador falso.

GetFakeRedactionCollector(IServiceProvider)

Obtiene la instancia del recopilador de redactores falso del contenedor de inserción de dependencias.

Se aplica a

Produto Versións
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Consulte también