Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

WebPart Classe

Serves as the base class for custom ASP.NET Web Parts controls, adding to the base Part class features some additional user interface (UI) properties, the ability to create connections, and personalization behavior.

Namespace:  System.Web.UI.WebControls.WebParts
Assembly:  System.Web (em System.Web. dll)

[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public abstract class WebPart : Part, IWebPart, 
	IWebActionable, IWebEditable

Quando você Criar os controles com funcionalidade Web Parts, você tem duas opções básicas.You can create custom controls that derive from the WebPart class, or you can create or use other server controls.Existing ASP.NET controls, custom server controls, and user controls can all be given full Web Parts functionality by declaring them within (or adding them programmatically to) a WebPartZone zone control, with the result that they will be wrapped with GenericWebPart objects at run time and treated as true WebPart controls.For details, see the documentation for the GenericWebPart class.Para Velocidade de desenvolvimento e a reutilização máxima do código, usando os controles de servidor existente pode ser uma boa opção.For maximum programmatic control over the behavior and Web Parts functionality of controls, creating a custom control that inherits from the WebPart class is often the best option.

The abstract WebPart class inherits from the base Part control and provides the basic elements for all WebPart controls.A classe inclui um conjunto comum de propriedades que afetam a aparência da interface do usuário.The AllowClose, AllowConnect, AllowEdit, AllowHide, AllowMinimize, and AllowZoneChange properties each specify whether the user of a Web application is permitted to interact with the part control in the way indicated by the given property name.The CatalogIconImageUrl, ChromeState, ChromeType, Description, Height, HelpUrl, Hidden, Title, TitleIconImageUrl, TitleUrl, and Width properties determine the size, visibility, appearance, and supporting content (such as a title and a description) for a WebPart control.

The relationship of a WebPart control to its context within the Web Parts control set is determined by properties such as WebPartManager, which holds a reference to the control's associated WebPartManager object, and Zone, which references the WebZone that contains the control.There can be only one WebPartManager control per page, and each instance of a WebPart control can reside within only one WebZone at a time.

Observação:

A WebPart control can be placed outside of a zone on a Web page, but in this case it functions as a normal server control and loses nearly all Web Parts functionality.

Several other important properties affect unique features of WebPart controls.The AuthorizationFilter property allows developers to set an arbitrary string that can be used as a filter at run time to determine whether a control is added to the page.Used together with a feature such as role management, the AuthorizationFilter property provides a useful mechanism for creating views based on defined user roles.The ExportMode property indicates whether, during an export, all the available property data on a control is exported, or only the non-sensitive data.Isso permite que os desenvolvedores distinguir entre os dados confidenciais e dados que não, são para fins de segurança.The WebBrowsableObject property returns a reference to an instance of a WebPart control, so that an EditorPart control can edit it when the page is in edit mode.Finalmente, há várias propriedades que indicam o status do Controlarar Relativo para o resto da página.The IsClosed property indicates whether a control is closed (and thus added to a PageCatalogPart object), or if it is open and available on the page.The IsShared property indicates whether a control is a shared control (versus a user-specific control), meaning that it is visible to all users of a Web page.The IsStandalone property indicates whether a control is currently contained in a WebPartZoneBase-derived zone (such as WebPartZone).A value of false indicates the control is inside a zone and thus has full Web Parts functionality.The IsStatic property indicates whether a control is static or dynamic.Um Controlarar estático é declarado na marcação de uma página da Web, enquanto um Controlarar dinâmico é adicionado por meio de programação.

The WebPart class also provides several methods that determine what happens at various points in the control's life cycle.For example, the OnConnectModeChanged and OnEditModeChanged methods can both be overridden in a derived class to provide programmatic control over the rendering of a control's contents during the event that corresponds to each method's name.

Classes that derive from WebPart can add WebPartVerb objects to the Verbs collection.The verbs are rendered in a verbs menu, which appears in the title bar of a WebPart control. WebPartVerb objects provide simple UI elements for common user actions such as hiding or minimizing the control or displaying Help.

The CreateEditorParts method creates a collection of any custom EditorPart controls that are associated with a WebPart control.Developers can override this method so that it creates custom controls designed specifically to edit their WebPart control.The method is called when a user clicks the edit verb on a WebPart control.

The following code example demonstrates how to create a WebPart control and reference it in a Web page.

The first part of the example contains the code for a custom WebPart control named TextDisplayWebPart.This control demonstrates how to create a simple custom WebPart control that gives you access to the features of the Web Parts control set. Para o exemplo de código para ser executado, você deve compilar este código-fonte. Você pode compilá-lo explicitamente e colocar o assembly resultante na pasta Bin do seu site da Web ou o cache de assembly global. Alternativamente, você pode colocar o código-fonte na pasta App_Code do seu site, onde será compilado dinamicamente em tempo de execução. This code example assumes that you compile the source code into an assembly, place it in a Bin subfolder of your Web application, and reference the assembly with a Register directive in your Web page.For a walkthrough that demonstrates both methods of compiling, see Passo-a-Passo: Desenvolvendo e usando um Controlar Servidor Personalizar.

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

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

     TextDisplayWebPart()
    {
      .AllowClose = ;
    }

    [Personalizable(), WebBrowsable]
     String ContentText
    {
       {  _contentText; }
       { _contentText = value; }
    }

       CreateChildControls()
    {
      Controls.Clear();
      DisplayContent =  Label();
      DisplayContent.BackColor = 
        System.Drawing.Color.LightBlue;
      DisplayContent.Text = .ContentText;
      .Controls.Add(DisplayContent);
      input =  TextBox();
      .Controls.Add(input);
      Button update =  Button();
      update.Text = ;
      update.Click +=  EventHandler(.submit_Click);
      .Controls.Add(update);
      ChildControlsCreated = ;
    }

      submit_Click(object sender, EventArgs e)
    {
      
       (input.Text != String.Empty)
      {
        _contentText = input.Text + @;
        input.Text = String.Empty;
        DisplayContent.Text = .ContentText;
      }
    }
  }
}


package Samples.AspNet.JSL.Controls;

import System.*;
import System.Security.Permissions.*;
import System.Web.*;
import System.Web.UI.WebControls.*;
import System.Web.UI.WebControls.WebParts.*;

/** @attribute AspNetHostingPermission(SecurityAction.Demand, Level =
    AspNetHostingPermissionLevel.Minimal)
 */
/** @attribute AspNetHostingPermission(SecurityAction.InheritanceDemand, Level =
    AspNetHostingPermissionLevel.Minimal)
 */
public class TextDisplayWebPart extends WebPart
{
    private String _contentText = null;
    private TextBox input;
    private Label displayContent;

    public TextDisplayWebPart()
    {
        this.set_AllowClose(false);
    } //TextDisplayWebPart

    /** @attribute Personalizable()
        @attribute WebBrowsable()
     */
    /** @property 
     */
    public String get_ContentText()
    {
        return _contentText;
    } //get_ContentText

    /** @property 
     */
    public void set_ContentText(String value)
    {
        _contentText = value;
    } //set_ContentText

    protected void CreateChildControls()
    {
        get_Controls().Clear();
        displayContent = new Label();
        displayContent.set_BackColor(System.Drawing.Color.get_LightBlue());
        displayContent.set_Text(this.get_ContentText());
        this.get_Controls().Add(displayContent);
        input = new TextBox();
        this.get_Controls().Add(input);
        Button update = new Button();
        update.set_Text("Set Label Content");
        update.add_Click(new EventHandler(this.Submit_Click));
        this.get_Controls().Add(update);
        set_ChildControlsCreated(true);
    } //CreateChildControls

    private void Submit_Click(Object sender, EventArgs e)
    {
        // Update the label string.
        if (!(input.get_Text().Equals(""))) {
            _contentText = input.get_Text() + "<br />";
            input.set_Text("");
            displayContent.set_Text(this.get_ContentText());
        }
    } //Submit_Click
} //TextDisplayWebPart


The second part of the example shows how to reference the TextDisplayWebPart control in an ASP.NET Web page.Notice that many of the various WebPart properties can be assigned declaratively to the custom control.

<%@ page language= %>
<%@ register tagprefix= 
             Namespace= 
             Assembly=%>

<!DOCTYPE html PUBLIC "-
    "http:
<html xmlns="http:
<head id= runat=>
    <title>ASP.NET Example</title>
</head>
<body>
  <form id= runat=>
    <asp:webpartmanager id= runat= />
    <asp:webpartzone
      id=
      runat=
      title=
      PartChromeType=>
        <parttitlestyle font-bold= ForeColor= />
        <partstyle
          borderwidth=   
          borderstyle=  
          bordercolor= />
        <zonetemplate>
          <aspSample:TextDisplayWebPart 
            runat=   
            id= 
            title =  />
        </zonetemplate>
    </asp:webpartzone>
  </form>
</body>
</html>


<%@ page language="VJ#" %>
<%@ register tagprefix="aspSample" 
             Namespace="Samples.AspNet.JSL.Controls" 
             Assembly="TextDisplayWebPartJSL"%>

<!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>


Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.

Contribuições da comunidade

ADICIONAR
Mostrar: