WebPart Constructor

Definición

Inicializa la clase para que la use una instancia de la clase heredada. A este constructor solo lo puede llamar una clase heredada.

protected:
 WebPart();
protected WebPart ();
Protected Sub New ()

Ejemplos

En el ejemplo de código siguiente se muestra cómo un control que deriva de la WebPart clase hereda los valores de propiedad predeterminados establecidos en el constructor base WebPart , pero después cambia el valor de una propiedad en el constructor del control derivado.

La primera parte de este ejemplo contiene el código de un control personalizado WebPart denominado TextDisplayWebPart. Este control muestra cómo crear un control personalizado WebPart sencillo que proporciona acceso a las características del conjunto de controles elementos web. Tenga en cuenta que, en el constructor del control personalizado, la TextDisplayWebPart.AllowClose propiedad se establece falseen , que tiene el efecto de impedir que los usuarios cierren el control en una página web. Para que se ejecute el ejemplo de código, debe compilar este código fuente. Puede compilarlo explícitamente y colocar el ensamblado resultante en la carpeta Bin del sitio web o en la caché global de ensamblados. Como alternativa, puede colocar el código fuente en la carpeta App_Code del sitio, donde se compilará dinámicamente en tiempo de ejecución. En este ejemplo de código se supone que se compila el código fuente en un ensamblado, se coloca en una subcarpeta Bin de la aplicación web y se hace referencia al ensamblado con una Register directiva en la página web. Para ver un tutorial que muestra ambos métodos de compilación, vea Walkthrough: Developing and Using a Custom Web Server Control.

using System;
using System.Security.Permissions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
  [AspNetHostingPermission(SecurityAction.Demand, 
    Level=AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand, 
    Level=AspNetHostingPermissionLevel.Minimal)]
  public class TextDisplayWebPart : WebPart
  {
    private String _contentText = null;
    TextBox input;
    Label DisplayContent;

    public TextDisplayWebPart()
    {
      this.AllowClose = false;
    }

    [Personalizable(), WebBrowsable]
    public String ContentText
    {
      get { return _contentText; }
      set { _contentText = value; }
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();
      DisplayContent = new Label();
      DisplayContent.BackColor = 
        System.Drawing.Color.LightBlue;
      DisplayContent.Text = this.ContentText;
      this.Controls.Add(DisplayContent);
      input = new TextBox();
      this.Controls.Add(input);
      Button update = new Button();
      update.Text = "Set Label Content";
      update.Click += new EventHandler(this.submit_Click);
      this.Controls.Add(update);
      ChildControlsCreated = true;
    }

    private void submit_Click(object sender, EventArgs e)
    {
      // Update the label string.
      if (!string.IsNullOrEmpty(input.Text))
      {
        _contentText = input.Text + @"<br />";
        input.Text = String.Empty;
        DisplayContent.Text = this.ContentText;
      }
    }
  }
}
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

<AspNetHostingPermission(SecurityAction.Demand, _
  Level := AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, _
  Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class TextDisplayWebPart
    Inherits WebPart
    Private _contentText As String = Nothing
    Private input As TextBox
    Private DisplayContent As Label
    
    
    Public Sub New() 
      Me.AllowClose = False
    End Sub
    
    <Personalizable(), WebBrowsable()>  _
    Public Property ContentText() As String 
        Get
            Return _contentText
        End Get
        Set
            _contentText = value
        End Set
    End Property
     
    Protected Overrides Sub CreateChildControls() 
        Controls.Clear()
        DisplayContent = New Label()
        DisplayContent.Text = Me.ContentText
        DisplayContent.BackColor = _
          System.Drawing.Color.LightBlue
        Me.Controls.Add(DisplayContent)
        input = New TextBox()
        Me.Controls.Add(input)
        Dim update As New Button()
        update.Text = "Set Label Content"
        AddHandler update.Click, AddressOf Me.submit_Click
        Me.Controls.Add(update)
        ChildControlsCreated = True
    
    End Sub
    
    
    Private Sub submit_Click(ByVal sender As Object, _
                             ByVal e As EventArgs) 
        ' Update the label string.
        If input.Text <> String.Empty Then
            _contentText = input.Text & "<br />"
            input.Text = String.Empty
            DisplayContent.Text = Me.ContentText
        End If
    
    End Sub
    
End Class

End Namespace

La segunda parte del ejemplo muestra cómo hacer referencia al TextDisplayWebPart control en una página web de ASP.NET. Después de cargar la página en un explorador, si hace clic en el menú verbos de la barra de título del control personalizado WebPart , el verbo close ahora está deshabilitado, lo que impide que los usuarios cierren el control.

<%@ page language="C#" %>
<%@ register tagprefix="aspSample" 
             Namespace="Samples.AspNet.CS.Controls" 
             Assembly="TextDisplayWebPartCS"%>

<!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 id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
  <form id="Form1" runat="server">
    <asp:webpartmanager id="WebPartManager1" runat="server" />
    <asp:webpartzone
      id="WebPartZone1"
      runat="server"
      title="Zone 1"
      PartChromeType="TitleAndBorder">
        <parttitlestyle font-bold="true" ForeColor="#3300cc" />
        <partstyle
          borderwidth="1px"   
          borderstyle="Solid"  
          bordercolor="#81AAF2" />
        <zonetemplate>
          <aspSample:TextDisplayWebPart 
            runat="server"   
            id="textwebpart" 
            title = "Text Content WebPart" />
        </zonetemplate>
    </asp:webpartzone>
  </form>
</body>
</html>
<%@ page language="VB" %>
<%@ register tagprefix="aspSample" 
             Namespace="Samples.AspNet.VB.Controls" 
             Assembly="TextDisplayWebPartVB"%>

<!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 id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
  <form id="Form1" runat="server">
    <asp:webpartmanager id="WebPartManager1" runat="server" />
    <asp:webpartzone
      id="WebPartZone1"
      runat="server"
      title="Zone 1"
      PartChromeType="TitleAndBorder">
        <parttitlestyle font-bold="true" ForeColor="#3300cc" />
        <partstyle
          borderwidth="1px"   
          borderstyle="Solid"  
          bordercolor="#81AAF2" />
        <zonetemplate>
          <aspSample:TextDisplayWebPart 
            runat="server"   
            id="textwebpart" 
            title = "Text Content WebPart" />
        </zonetemplate>
    </asp:webpartzone>
  </form>
</body>
</html>

Comentarios

El WebPart constructor inicializa los valores predeterminados para varias propiedades orientadas a la interfaz de usuario, incluidas las distintas Allow propiedades que determinan las funcionalidades del control. Estas propiedades se incorporan a continuación en una instancia de clase heredada.

Se aplica a

Consulte también