ImportCatalogPart.GetAvailableWebPartDescriptions Metodo

Definizione

Restituisce un insieme di descrizioni dei controlli WebPart disponibili in un catalogo.

public:
 override System::Web::UI::WebControls::WebParts::WebPartDescriptionCollection ^ GetAvailableWebPartDescriptions();
public override System.Web.UI.WebControls.WebParts.WebPartDescriptionCollection GetAvailableWebPartDescriptions ();
override this.GetAvailableWebPartDescriptions : unit -> System.Web.UI.WebControls.WebParts.WebPartDescriptionCollection
Public Overrides Function GetAvailableWebPartDescriptions () As WebPartDescriptionCollection

Restituisce

WebPartDescriptionCollection

Oggetto WebPartDescriptionCollection che contiene un oggetto WebPartDescription per ogni controllo di un catalogo.

Esempio

Nell'esempio di codice seguente viene illustrato come usare il GetAvailableWebPartDescriptions metodo in una pagina Web. L'esempio ha quattro parti:

  • Controllo utente che consente di modificare le modalità di visualizzazione in una pagina di Web part.

  • Pagina Web che contiene un CatalogZone controllo e un ImportCatalogPart controllo, insieme al codice che usa il GetAvailableWebPartDescriptions metodo .

  • File di codice sorgente che contiene due controlli personalizzati WebPart .

  • Spiegazione del funzionamento dell'esempio quando si carica la pagina in un browser.

La prima parte di questo esempio di codice è il controllo utente che consente agli utenti di modificare le modalità di visualizzazione in una pagina Web. Inserire il codice sorgente seguente in un file e denominarlo Displaymodemenucs.ascx o Displaymodemenuvb.ascx (a seconda della lingua in uso). Per informazioni dettagliate sulle modalità di visualizzazione e una descrizione del codice sorgente in questo controllo, vedere Procedura dettagliata: Modifica delle modalità di visualizzazione in una pagina Web part.

<%@ control language="C#" classname="DisplayModeMenuCS"%>
<script runat="server">
  
 // Use a field to reference the current WebPartManager.
  WebPartManager _manager;

  void Page_Init(object sender, EventArgs e)
  {
    Page.InitComplete += new EventHandler(InitComplete);
    
  }  

  void InitComplete(object sender, System.EventArgs e)
  {
    _manager = WebPartManager.GetCurrentWebPartManager(Page);

    String browseModeName = WebPartManager.BrowseDisplayMode.Name;

    // Fill the dropdown with the names of supported display modes.
    foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes)
    {
      String modeName = mode.Name;
      // Make sure a mode is enabled before adding it.
      if (mode.IsEnabled(_manager))
      {
        ListItem item = new ListItem(modeName, modeName);
        DisplayModeDropdown.Items.Add(item);
      }
    }

    // If shared scope is allowed for this user, display the scope-switching
    // UI and select the appropriate radio button for the current user scope.
    if (_manager.Personalization.CanEnterSharedScope)
    {
      Panel2.Visible = true;
      if (_manager.Personalization.Scope == PersonalizationScope.User)
        RadioButton1.Checked = true;
      else
        RadioButton2.Checked = true;
    }
    
  }
 
  // Change the page to the selected display mode.
  void DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e)
  {
    String selectedMode = DisplayModeDropdown.SelectedValue;

    WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode];
    if (mode != null)
      _manager.DisplayMode = mode;
  }

  // Set the selected item equal to the current display mode.
  void Page_PreRender(object sender, EventArgs e)
  {
    ListItemCollection items = DisplayModeDropdown.Items;
    int selectedIndex = 
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
    DisplayModeDropdown.SelectedIndex = selectedIndex;
  }

  // Reset all of a user's personalization data for the page.
  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    _manager.Personalization.ResetPersonalizationState();
  }

  // If not in User personalization scope, toggle into it.
  protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.Scope == PersonalizationScope.Shared)
      _manager.Personalization.ToggleScope();
  }

  // If not in Shared scope, and if user is allowed, toggle the scope.
  protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
  {
    if (_manager.Personalization.CanEnterSharedScope && 
        _manager.Personalization.Scope == PersonalizationScope.User)
      _manager.Personalization.ToggleScope();
  }
</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text="&nbsp;Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>
<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
  ' Use a field to reference the current WebPartManager.
  Dim _manager As WebPartManager

  Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    AddHandler Page.InitComplete, AddressOf InitComplete
  End Sub

  Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)
    _manager = WebPartManager.GetCurrentWebPartManager(Page)
      
    Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
      
    ' Fill the dropdown with the names of supported display modes.
    Dim mode As WebPartDisplayMode
    For Each mode In _manager.SupportedDisplayModes
      Dim modeName As String = mode.Name
      ' Make sure a mode is enabled before adding it.
      If mode.IsEnabled(_manager) Then
        Dim item As New ListItem(modeName, modeName)
        DisplayModeDropdown.Items.Add(item)
      End If
    Next mode
      
    ' If shared scope is allowed for this user, display the scope-switching
    ' UI and select the appropriate radio button for the current user scope.
    If _manager.Personalization.CanEnterSharedScope Then
      Panel2.Visible = True
      If _manager.Personalization.Scope = PersonalizationScope.User Then
        RadioButton1.Checked = True
      Else
        RadioButton2.Checked = True
      End If
    End If
   
  End Sub

  ' Change the page to the selected display mode.
  Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    Dim selectedMode As String = DisplayModeDropdown.SelectedValue   
    Dim mode As WebPartDisplayMode = _
      _manager.SupportedDisplayModes(selectedMode)
    If Not (mode Is Nothing) Then
      _manager.DisplayMode = mode
    End If

  End Sub
   
  ' Set the selected item equal to the current display mode.
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    Dim items As ListItemCollection = DisplayModeDropdown.Items
    Dim selectedIndex As Integer = _
      items.IndexOf(items.FindByText(_manager.DisplayMode.Name))
    DisplayModeDropdown.SelectedIndex = selectedIndex

  End Sub

  ' Reset all of a user's personalization data for the page.
  Protected Sub LinkButton1_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    _manager.Personalization.ResetPersonalizationState()
    
  End Sub

  ' If not in User personalization scope, toggle into it.
  Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.Scope = PersonalizationScope.Shared Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub
   
  ' If not in Shared scope, and if user is allowed, toggle the scope.
  Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
    
    If _manager.Personalization.CanEnterSharedScope AndAlso _
      _manager.Personalization.Scope = PersonalizationScope.User Then
      _manager.Personalization.ToggleScope()
    End If

  End Sub

</script>
<div>
  <asp:Panel ID="Panel1" runat="server" 
    Borderwidth="1" 
    Width="230" 
    BackColor="lightgray"
    Font-Names="Verdana, Arial, Sans Serif" >
    <asp:Label ID="Label1" runat="server" 
      Text="&nbsp;Display Mode" 
      Font-Bold="true"
      Font-Size="8"
      Width="120" 
      AssociatedControlID="DisplayModeDropdown"/>
    <asp:DropDownList ID="DisplayModeDropdown" runat="server"  
      AutoPostBack="true" 
      Width="120"
      OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
    <asp:LinkButton ID="LinkButton1" runat="server"
      Text="Reset User State" 
      ToolTip="Reset the current user's personalization data for the page."
      Font-Size="8" 
      OnClick="LinkButton1_Click" />
    <asp:Panel ID="Panel2" runat="server" 
      GroupingText="Personalization Scope"
      Font-Bold="true"
      Font-Size="8" 
      Visible="false" >
      <asp:RadioButton ID="RadioButton1" runat="server" 
        Text="User" 
        AutoPostBack="true"
        GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
      <asp:RadioButton ID="RadioButton2" runat="server" 
        Text="Shared" 
        AutoPostBack="true"
        GroupName="Scope" 
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    </asp:Panel>
  </asp:Panel>
</div>

La seconda parte dell'esempio di codice è la pagina Web. Nella parte superiore della pagina sono presenti due register direttive, una per il controllo utente e una per il componente compilato che contiene i due controlli personalizzati WebPart . A entrambi questi controlli viene fatto riferimento in modo dichiarativo nel markup della pagina. Nei riferimenti dichiarativi ai WebPart controlli (entrambi iniziano con un aspSample prefisso), si noti che a ognuno è stato aggiunto un exportMode="all" attributo. Questo attributo consente di esportare un oggetto . File di descrizione webpart per il controllo, che verrà usato in un passaggio successivo per importare il controllo in una pagina.

Nota

Per consentire agli utenti di un'applicazione di Web part di esportare un file di descrizione per WebPart i controlli, è necessario abilitare anche la funzionalità di esportazione nell'applicazione Web aggiungendo un enableExport="true" attributo all'elemento <webParts> (figlio dell'elemento<system.web>) nel file Web.config. L'esportazione è disabilitata per impostazione predefinita, quindi se non è ancora stata abilitata l'esportazione per l'applicazione, modificare il file di Web.config e farlo ora.

La pagina Web include anche un riferimento dichiarativo al ImportCatalogPart controllo, annidato all'interno della gerarchia appropriata di elementi dichiarativi. Il GetAvailableWebPartDescriptions metodo viene chiamato all'interno del codice per il Button1_Click metodo .

<%@ page language="c#" %>
<%@ register TagPrefix="uc1" 
  TagName="DisplayModeMenuCS" 
  Src="DisplayModeMenuCS.ascx" %>
<%@ register tagprefix="aspSample" 
  Namespace="Samples.AspNet.CS.Controls" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  // <snippet3>
  protected void Button1_Click(object sender, EventArgs e)
  {
    WebPartDescriptionCollection descriptions =
      ImportCatalogPart1.GetAvailableWebPartDescriptions();
    StringBuilder descriptionContent = new StringBuilder();
    foreach (WebPartDescription description in descriptions)
    {
      descriptionContent.AppendLine("<div><br /><strong>" + description.Title +
        "</strong><br />");
      descriptionContent.AppendLine("&nbsp;ID: " + description.ID + "<br />");
      descriptionContent.AppendLine("&nbsp;Description: " +
        description.Description + "<br /></div><hr />");
    }

    Label1.Text = "<h3>Catalog Contents</h3>" + descriptionContent.ToString();     

  }
  // </snippet3>

  // <snippet4>
  protected void Button2_Click(object sender, EventArgs e)
  {
    WebPartDescriptionCollection descriptions =
      ImportCatalogPart1.GetAvailableWebPartDescriptions();

    if (descriptions.Count > 0)
    {
      WebPart partToAdd =
        ImportCatalogPart1.GetWebPart(descriptions[0]);
      WebPartManager1.AddWebPart(partToAdd, zone1, 0);
    }
  }
  // </snippet4>
  
  protected void Page_Load(object sender, EventArgs e)
  {
    Button1.Visible = false;
    Button2.Visible = false;
    Label1.Visible = false;
  }

  protected void ImportCatalogPart1_PreRender(object sender, 
    EventArgs e)
  {
    Button1.Visible = true;
    Button2.Visible = true;
    Label1.Visible = true;
  }


</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>
      ImportCatalogPart Control
    </title>
  </head>
  <body>
    <form id="form1" runat="server">
      <asp:webpartmanager id="WebPartManager1" runat="server"  />
      <uc1:DisplayModeMenuCS ID="DisplayModeMenu1" runat="server" />
      <asp:webpartzone id="zone1" runat="server" >
        <PartTitleStyle BorderWidth="1"
          Font-Names="Verdana, Arial"
          Font-Size="110%"
          BackColor="LightBlue" />
        <zonetemplate>
          <asp:Calendar ID="Calendar1" runat="server" Title="My Calendar" />
          <aspsample:textdisplaywebpart id="wp1" runat="server" 
            Title="Text Display WebPart" exportmode="all" 
            description="Dynamically displays text in a label"/>
          <aspsample:userinfowebpart id="wp2" runat="server" 
            Title="User Info WebPart" exportmode="all" 
            description="Gathers user information" />
        </zonetemplate>
      </asp:webpartzone> 
      <asp:CatalogZone ID="CatalogZone1" runat="server">
        <ZoneTemplate>
          <asp:ImportCatalogPart ID="ImportCatalogPart1" 
            runat="server" 
            OnPreRender="ImportCatalogPart1_PreRender" />
        </ZoneTemplate>
      </asp:CatalogZone>
      <hr />
      <asp:Button ID="Button1" runat="server" 
        Text="Get WebPart Description" 
        OnClick="Button1_Click" />
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="Use GetWebPart" 
        OnClick="Button2_Click" />
      <asp:Label ID="Label1" runat="server" Text=""></asp:Label>  
    </form>
  </body>
</html>
<%@ page language="vb" %>
<%@ register TagPrefix="uc1" 
  TagName="DisplayModeMenuVB" 
  Src="DisplayModeMenuVB.ascx" %>
<%@ register tagprefix="aspSample" 
  Namespace="Samples.AspNet.VB.Controls" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

' <snippet3>
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim descriptions As WebPartDescriptionCollection = _
      ImportCatalogPart1.GetAvailableWebPartDescriptions()
    Dim descriptionContent As StringBuilder = New StringBuilder()
    Dim description As WebPartDescription
    For Each description In descriptions
      descriptionContent.AppendLine("<div><br /><strong>" + _
        description.Title + "</strong><br />")
      descriptionContent.AppendLine("&nbsp;ID: " + _
        description.ID + "<br />")
      descriptionContent.AppendLine("&nbsp;Description: " + _
        description.Description + "<br /></div><hr />")
    Next description

    Label1.Text = "<h3>Catalog Contents</h3>" + descriptionContent.ToString()
End Sub
' </snippet3>

' <snippet4>
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim descriptions As WebPartDescriptionCollection = _
      ImportCatalogPart1.GetAvailableWebPartDescriptions
    If (descriptions.Count > 0) Then
        Dim partToAdd As WebPart = ImportCatalogPart1.GetWebPart(descriptions(0))
        WebPartManager1.AddWebPart(partToAdd, zone1, 0)
    End If
End Sub
' </snippet4>

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Button1.Visible = false
    Button2.Visible = false
    Label1.Visible = false
End Sub

Protected Sub ImportCatalogPart1_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    Button1.Visible = true
    Button2.Visible = true
    Label1.Visible = true
End Sub

</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>
      ImportCatalogPart Control
    </title>
  </head>
  <body>
    <form id="form1" runat="server">
      <asp:webpartmanager id="WebPartManager1" runat="server"  />
      <uc1:DisplayModeMenuVB ID="DisplayModeMenu1" runat="server" />
      <asp:webpartzone id="zone1" runat="server" >
        <PartTitleStyle BorderWidth="1"
          Font-Names="Verdana, Arial"
          Font-Size="110%"
          BackColor="LightBlue" />
        <zonetemplate>
          <asp:Calendar ID="Calendar1" runat="server" Title="My Calendar" />
          <aspsample:textdisplaywebpart id="wp1" runat="server" 
            Title="Text Display WebPart" exportmode="all" 
            description="Dynamically displays text in a label"/>
          <aspsample:userinfowebpart id="wp2" runat="server" 
            Title="User Info WebPart" exportmode="all" 
            description="Gathers user information" />
        </zonetemplate>
      </asp:webpartzone> 
      <asp:CatalogZone ID="CatalogZone1" runat="server">
        <ZoneTemplate>
          <asp:ImportCatalogPart ID="ImportCatalogPart1" 
            runat="server" 
            OnPreRender="ImportCatalogPart1_PreRender" />
        </ZoneTemplate>
      </asp:CatalogZone>
      <hr />
      <asp:Button ID="Button1" runat="server" 
        Text="Get WebPart Description" 
        OnClick="Button1_Click" />
      <br />
      <asp:Button ID="Button2" runat="server" 
        Text="Use GetWebPart" 
        OnClick="Button2_Click" />
      <asp:Label ID="Label1" runat="server" Text=""></asp:Label>  
    </form>
  </body>
</html>

La terza parte dell'esempio di codice è il codice sorgente per i due WebPart controlli. Per eseguire l'esempio di codice, è necessario compilare questo codice sorgente. È possibile compilarlo in modo esplicito e inserire l'assembly risultante nella cartella Bin del sito Web o nella Global Assembly Cache. In alternativa, è possibile inserire il codice sorgente nella cartella App_Code del sito, in cui verrà compilato in modo dinamico in fase di esecuzione. In questo esempio di codice viene usata la compilazione dinamica. Per una procedura dettagliata che illustra entrambi i metodi di compilazione, vedere Procedura dettagliata: sviluppo e uso di un controllo server Web personalizzato.

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
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 UserInfoWebPart : WebPart
  {
    HttpServerUtility server = HttpContext.Current.Server;
    private String _userNickName = "Add a nickname.";
    private String _userPetName = "Add a pet's name.";
    private DateTime _userSpecialDate = DateTime.Now;
    private Boolean _userIsCurrent = true;
    private JobTypeName _userJobType = JobTypeName.Unselected;
    public enum JobTypeName
    {
      Unselected = 0,
      Support = 1,
      Service = 2,
      Professional = 3, 
      Technical = 4,
      Manager = 5,
      Executive = 6
    }
    Label NickNameLabel;
    Label PetNameLabel;
    Label SpecialDateLabel;
    CheckBox IsCurrentCheckBox;
    Label JobTypeLabel;

    // Add the Personalizable and WebBrowsable attributes to the  
    // public properties, so that users can save property values  
    // and edit them with a PropertyGridEditorPart control.
    [Personalizable(), WebBrowsable, WebDisplayName("Nickname")]
    public String NickName
    {
      get 
      { 
        object o = ViewState["NickName"];
        if (o != null)
          return (string)o;
        else
          return _userNickName;        
      } 

      set { _userNickName = server.HtmlEncode(value); }
    }

    [Personalizable(), WebBrowsable, WebDisplayName("Pet Name")]
    public String PetName
    {
      get 
      { 
        object o = ViewState["PetName"];
        if (o != null)
          return (string)o;
        else
          return _userPetName;        
      }

      set { _userPetName = server.HtmlEncode(value); }
    }

    [Personalizable(), WebBrowsable(), WebDisplayName("Special Day")]
    public DateTime SpecialDay
    {
      get
      {
        object o = ViewState["SpecialDay"];
        if (o != null)
          return (DateTime)o;
        else
          return _userSpecialDate;
      }

      set { _userSpecialDate = value; }
    }

    [Personalizable(), WebBrowsable(), WebDisplayName("Job Type")]
    public JobTypeName UserJobType
    {
      get
      {
        object o = ViewState["UserJobType"];
        if (o != null)
          return (JobTypeName)o;
        else
          return _userJobType;
      }

      set { _userJobType = (JobTypeName)value; }
    }

    [Personalizable(), WebBrowsable(), WebDisplayName("Is Current")]
    public Boolean IsCurrent
    {
      get
      {
        object o = ViewState["IsCurrent"];
        if (o != null)
          return (Boolean)o;
        else
          return _userIsCurrent;
      }

      set { _userIsCurrent = value; }
    }

    protected override void CreateChildControls()
    {
      Controls.Clear();

      NickNameLabel = new Label();
      NickNameLabel.Text = this.NickName;
      SetControlAttributes(NickNameLabel);

      PetNameLabel = new Label();
      PetNameLabel.Text = this.PetName;
      SetControlAttributes(PetNameLabel);

      SpecialDateLabel = new Label();
      SpecialDateLabel.Text = this.SpecialDay.ToShortDateString();
      SetControlAttributes(SpecialDateLabel);

      IsCurrentCheckBox = new CheckBox();
      IsCurrentCheckBox.Checked = this.IsCurrent;
      SetControlAttributes(IsCurrentCheckBox);

      JobTypeLabel = new Label();
      JobTypeLabel.Text = this.UserJobType.ToString();
      SetControlAttributes(JobTypeLabel);

      ChildControlsCreated = true;
    }

    private void SetControlAttributes(WebControl ctl)
    {
      ctl.BackColor = Color.White;
      ctl.BorderWidth = 1;
      ctl.Width = 200;
      this.Controls.Add(ctl);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
      writer.Write("Nickname:");
      writer.WriteBreak();
      NickNameLabel.RenderControl(writer);
      writer.WriteBreak();
      writer.Write("Pet Name:");
      writer.WriteBreak();
      PetNameLabel.RenderControl(writer);
      writer.WriteBreak();
      writer.Write("Special Date:");
      writer.WriteBreak();
      SpecialDateLabel.RenderControl(writer);
      writer.WriteBreak();
      writer.Write("Job Type:");
      writer.WriteBreak();
      JobTypeLabel.RenderControl(writer);
      writer.WriteBreak();
      writer.Write("Current:");
      writer.WriteBreak();
      IsCurrentCheckBox.RenderControl(writer);
    }
  }

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

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

    protected override void CreateChildControls()
    {
      Controls.Clear();
      DisplayContent = new Label();
      DisplayContent.BackColor = Color.LightBlue;
      DisplayContent.Text = this.ContentText;
      this.Controls.Add(DisplayContent);

      lineBreak = new Literal();
      lineBreak.Text = @"<br />";
      Controls.Add(lineBreak);

      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);
    }

    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.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
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 UserInfoWebPart
    Inherits WebPart
    Private server As HttpServerUtility = HttpContext.Current.Server
    Private _userNickName As String = "Add a nickname."
    Private _userPetName As String = "Add a pet's name."
    Private _userSpecialDate As DateTime = DateTime.Now
    Private _userIsCurrent As [Boolean] = True
    Private _userJobType As JobTypeName = JobTypeName.Unselected

    Public Enum JobTypeName
      Unselected = 0
      Support = 1
      Service = 2
      Professional = 3
      Technical = 4
      Manager = 5
      Executive = 6
    End Enum

    Private NickNameLabel As Label
    Private PetNameLabel As Label
    Private SpecialDateLabel As Label
    Private IsCurrentCheckBox As CheckBox
    Private JobTypeLabel As Label

    ' Add the Personalizable and WebBrowsable attributes to the  
    ' public properties, so that users can save property values  
    ' and edit them with a PropertyGridEditorPart control.

    <Personalizable(), WebBrowsable(), WebDisplayName("Nickname")> _
    Public Property NickName() As String
      Get
        Dim o As Object = ViewState("NickName")
        If Not (o Is Nothing) Then
          Return CStr(o)
        Else
          Return _userNickName
        End If
      End Get
      Set(ByVal value As String)
        _userNickName = server.HtmlEncode(value)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Pet Name")> _
    Public Property PetName() As String
      Get
        Dim o As Object = ViewState("PetName")
        If Not (o Is Nothing) Then
          Return CStr(o)
        Else
          Return _userPetName
        End If
      End Get
      Set(ByVal value As String)
        _userPetName = server.HtmlEncode(value)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Special Day")> _
    Public Property SpecialDay() As DateTime
      Get
        Dim o As Object = ViewState("SpecialDay")
        If Not (o Is Nothing) Then
          Return CType(o, DateTime)
        Else
          Return _userSpecialDate
        End If
      End Get

      Set(ByVal value As DateTime)
        _userSpecialDate = value
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Job Type")> _
    Public Property UserJobType() As JobTypeName
      Get
        Dim o As Object = ViewState("UserJobType")
        If Not (o Is Nothing) Then
          Return CType(o, JobTypeName)
        Else
          Return _userJobType
        End If
      End Get
      Set(ByVal value As JobTypeName)
        _userJobType = CType(value, JobTypeName)
      End Set
    End Property

    <Personalizable(), WebBrowsable(), WebDisplayName("Is Current")> _
    Public Property IsCurrent() As [Boolean]
      Get
        Dim o As Object = ViewState("IsCurrent")
        If Not (o Is Nothing) Then
          Return CType(o, [Boolean])
        Else
          Return _userIsCurrent
        End If
      End Get
      Set(ByVal value As [Boolean])
        _userIsCurrent = value
      End Set
    End Property

    Protected Overrides Sub CreateChildControls()
      Controls.Clear()

      NickNameLabel = New Label()
      NickNameLabel.Text = Me.NickName
      SetControlAttributes(NickNameLabel)

      PetNameLabel = New Label()
      PetNameLabel.Text = Me.PetName
      SetControlAttributes(PetNameLabel)

      SpecialDateLabel = New Label()
      SpecialDateLabel.Text = Me.SpecialDay.ToShortDateString()
      SetControlAttributes(SpecialDateLabel)

      IsCurrentCheckBox = New CheckBox()
      IsCurrentCheckBox.Checked = Me.IsCurrent
      SetControlAttributes(IsCurrentCheckBox)

      JobTypeLabel = New Label()
      JobTypeLabel.Text = Me.UserJobType.ToString()
      SetControlAttributes(JobTypeLabel)

      ChildControlsCreated = True

    End Sub

    Private Sub SetControlAttributes(ByVal ctl As WebControl)
      ctl.BackColor = Color.White
      ctl.BorderWidth = 1
      ctl.Width = 200
      Me.Controls.Add(ctl)
    End Sub

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
      writer.Write("Nickname:")
      writer.WriteBreak()
      NickNameLabel.RenderControl(writer)
      writer.WriteBreak()
      writer.Write("Pet Name:")
      writer.WriteBreak()
      PetNameLabel.RenderControl(writer)
      writer.WriteBreak()
      writer.Write("Special Date:")
      writer.WriteBreak()
      SpecialDateLabel.RenderControl(writer)
      writer.WriteBreak()
      writer.Write("Job Type:")
      writer.WriteBreak()
      JobTypeLabel.RenderControl(writer)
      writer.WriteBreak()
      writer.Write("Current:")
      writer.WriteBreak()
      IsCurrentCheckBox.RenderControl(writer)

    End Sub

  End Class


  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TextDisplayWebPart
    Inherits WebPart
    Private _contentText As String = Nothing
    Private _fontStyle As String = Nothing
    Private input As TextBox
    Private DisplayContent As Label
    Private lineBreak As Literal

    <Personalizable(), WebBrowsable()> _
    Public Property ContentText() As String
      Get
        Return _contentText
      End Get
      Set(ByVal value As String)
        _contentText = value
      End Set
    End Property

    Protected Overrides Sub CreateChildControls()
      Controls.Clear()
      DisplayContent = New Label()
      DisplayContent.BackColor = Color.LightBlue
      DisplayContent.Text = Me.ContentText
      Me.Controls.Add(DisplayContent)

      lineBreak = New Literal()
      lineBreak.Text = "<br />"
      Controls.Add(lineBreak)

      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)

    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

Eseguire ora l'esempio di codice. Caricare la pagina Web in un browser. Il primo passaggio consiste nell'esportare un oggetto . File di descrizione webpart per ogni WebPart controllo (per TextDisplayWebPart e per il UserInfoWebPart controllo). Per ogni controllo, fare clic sul menu verbi nel controllo (rappresentato dalla freccia rivolta verso il basso nella barra del titolo) e fare clic su Esporta. Seguire le istruzioni per salvare un oggetto . File di descrizione webpart per il controllo. Dopo aver esportato un file di descrizione per ogni controllo, chiudere la pagina Web e modificare l'origine della pagina in un editor. Eliminare gli <aspSample:userinfowebpart> elementi e la dichiarazione del <aspSample:textdisplaywebpart> controllo, quindi salvare e chiudere il file. Questa procedura consente di simulare un utente che non dispone ancora di questi controlli, quindi è possibile importare i controlli nella pagina.

Caricare di nuovo la pagina Web in un browser. Usare il controllo elenco a discesa Modalità di visualizzazione e selezionare Catalogo per passare alla modalità catalogo. ImportCatalogPart Nel controllo fare clic sul pulsante Sfoglia, passare a . File WebPart creati, selezionare uno, quindi fare clic sul pulsante Upload. Accanto al controllo verrà visualizzato un riferimento al controllo con una casella di controllo. Selezionare la casella di controllo e quindi fare clic su Aggiungi per aggiungere il controllo alla pagina. Ripetere questo processo per l'altro controllo.

Mentre si è in questa visualizzazione della pagina, fare clic sul pulsante Get WebPart Description (Ottieni descrizione webpart ) nella parte inferiore della pagina per visualizzare l'effetto dell'accesso a livello di codice all'oggetto WebPartDescription per la descrizione del controllo attualmente caricata nel ImportCatalogPart controllo. Il metodo utilizzato per accedere ai dettagli della descrizione, trovato nel Button1_Click metodo dell'origine della pagina, è il GetAvailableWebPartDescriptions metodo . Un'etichetta sotto il pulsante visualizza i dettagli di base sul controllo.

Dopo aver aggiunto il primo controllo, ripetere il processo per aggiungere il secondo controllo alla pagina. Infine, fare clic su Chiudi per uscire dalla modalità catalogo e restituire la pagina per la modalità di esplorazione. Entrambi i controlli personalizzati dovrebbero ora essere visualizzati nella pagina, contenente i valori presenti durante l'esportazione dei file di descrizione in precedenza.

Commenti

Il GetAvailableWebPartDescriptions metodo fornisce un'implementazione per il metodo di base astratto dichiarato nella CatalogPart classe . Il GetAvailableWebPartDescriptions metodo restituisce informazioni di descrizione per ogni controllo in un catalogo. Si noti che nel caso di un ImportCatalogPart controllo può essere presente un solo controllo server nel catalogo alla volta, anche se il metodo funziona se sono presenti più controlli.

Un WebPartDescription oggetto è un oggetto che contiene informazioni essenziali su un WebPart controllo, incluso il relativo ID, un riferimento all'oggetto al controllo e i valori di diverse proprietà importanti ereditate dalla Part classe , ad esempio Title e Description.

Il GetAvailableWebPartDescriptions metodo migliora le prestazioni. Quando viene creato un catalogo, sono necessarie alcune informazioni su ogni controllo che contiene, tra cui un titolo, una descrizione, un'icona (se presente) e un ID. Invece di creare un'istanza di ogni controllo per ottenere queste informazioni, una CatalogZoneBase zona che crea un catalogo chiama il GetAvailableWebPartDescriptions metodo e la chiamata restituisce solo le informazioni di descrizione per il controllo anziché un'istanza del controllo.

Si applica a

Vedi anche