CatalogPartCollection Classe
Definição
Contém uma coleção de controles de CatalogPart usados para fornecer catálogos de controles de servidor Web que os usuários finais podem adicionar a uma página da Web.Contains a collection of CatalogPart controls used to provide catalogs of Web server controls that end users can add to a Web page. Essa classe não pode ser herdada.This class cannot be inherited.
public ref class CatalogPartCollection sealed : System::Collections::ReadOnlyCollectionBase
public sealed class CatalogPartCollection : System.Collections.ReadOnlyCollectionBase
type CatalogPartCollection = class
inherit ReadOnlyCollectionBase
Public NotInheritable Class CatalogPartCollection
Inherits ReadOnlyCollectionBase
- Herança
Exemplos
O exemplo de código a seguir demonstra vários usos da CatalogPartCollection classe.The following code example demonstrates several uses of the CatalogPartCollection class. Há quatro partes para este exemplo de código:There are four parts to this code example:
Um controle de usuário que permite alterar modos de exibição em uma página Web Parts.A user control that enables you to change display modes on a Web Parts page.
Uma classe para um WebPart controle personalizado chamado
TextDisplayWebPart, que é referenciado na página da Web e está contido em um dos CatalogPart controles.A class for a custom WebPart control namedTextDisplayWebPart, which is referenced in the Web page and is contained in one of the CatalogPart controls.Uma página da Web que faz referência ao
TextDisplayWebPartcontrole, contém um CatalogZone controle com dois dos CatalogPart controles do conjunto de controle Web Parts declarado na zona e contém o código controlado por eventos para criar e manipular um CatalogPartCollection objeto.A Web page that references theTextDisplayWebPartcontrol, contains a CatalogZone control with two of the CatalogPart controls from the Web Parts control set declared in the zone, and contains event-driven code to create and manipulate a CatalogPartCollection object.Uma explicação de como o exemplo de código funciona quando você o carrega em um navegador.An explanation of how the code example works when you load it in a browser.
A primeira parte do exemplo de código é o controle de usuário.The first part of the code example is the user control. O código-fonte do controle de usuário vem de outro tópico.The source code for the user control comes from another topic. Para que este exemplo de código funcione, você precisa obter o arquivo. ascx para o controle de usuário do passo a passos: alterando os modos de exibição em um tópico de Web Parts página e coloque o arquivo na mesma pasta que a página. aspx neste exemplo de código.For this code example to work, you need to obtain the .ascx file for the user control from the Walkthrough: Changing Display Modes on a Web Parts Page topic, and place the file in the same folder as the .aspx page in this code example.
A segunda parte do exemplo de código é o TextDisplayWebPart controle.The second part of the code example is the TextDisplayWebPart control. Para que o exemplo de código seja executado, você deve compilar esse código-fonte.For the code example to run, you must compile this source code. Você pode compilá-lo explicitamente e colocar o assembly resultante na pasta bin do seu site ou no cache de assembly global.You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Como alternativa, você pode colocar o código-fonte na pasta App_Code do seu site, onde ele será compilado dinamicamente em tempo de execução.Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. Para obter instruções que demonstram os dois métodos de compilação, consulte passo a passos: desenvolvendo e usando um controle de servidor Web personalizado.For a walkthrough that demonstrates both methods of compiling, see Walkthrough: Developing and Using a Custom Web Server Control. Observe que o controle tem uma propriedade chamada ContentText ; essa propriedade contém o valor que o usuário insere na caixa de texto.Note that the control has a property named ContentText; this property holds the value that the user enters in the text box.
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 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 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
A terceira parte do exemplo de código é a página da Web.The third part of the code example is the Web page. Observe que o <asp:catalogzone> elemento da página contém declarações para dois CatalogPart controles.Notice that the <asp:catalogzone> element for the page contains declarations for two CatalogPart controls. Esses controles se tornam parte de um CatalogPartCollection objeto personalizado que é criado quando o Button1_Click método é executado.These controls become part of a custom CatalogPartCollection object that is created when the Button1_Click method executes. O PageCatalogPart controle contém controles de servidor Web que foram previamente fechados por um usuário em tempo de execução.The PageCatalogPart control contains Web server controls that have been previously closed by a user at run time. Controles no PageCatalogPart controle podem ser adicionados de volta a uma página.Controls in the PageCatalogPart control can be added back to a page. O DeclarativeCatalogPart controle contém uma declaração do controle personalizado TextDisplayWebPart .The DeclarativeCatalogPart control contains a declaration of the custom TextDisplayWebPart control. Quando a página está no modo de catálogo, um usuário pode adicionar o TextDisplayWebPart controle à página para que possa ser usado no modo de procura normal.When the page is in catalog mode, a user can add the TextDisplayWebPart control to the page so that it can be used in normal browse mode.
<%@ Page Language="C#" %>
<%@ register TagPrefix="uc1"
TagName="DisplayModeMenuCS"
Src="DisplayModeMenuCS.ascx" %>
<%@ 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">
<script runat="server">
// <snippet2>
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList(2);
list.Add(PageCatalogPart1);
list.Add(DeclarativeCatalogPart1);
// Pass an ICollection object to the constructor.
CatalogPartCollection myParts = new CatalogPartCollection(list);
foreach (CatalogPart catalog in myParts)
{
catalog.Description = "My " + catalog.DisplayTitle;
}
// Use the IndexOf property to locate a CatalogPart control.
int PageCatalogPartIndex = myParts.IndexOf(PageCatalogPart1);
myParts[PageCatalogPartIndex].ChromeType = PartChromeType.TitleOnly;
// Use the Contains method to see if a CatalogPart control exists.
if (myParts.Contains(PageCatalogPart1))
{
WebPart closedWebPart = null;
WebPartDescriptionCollection descriptions = PageCatalogPart1.GetAvailableWebPartDescriptions();
if (descriptions.Count > 0)
{
closedWebPart = PageCatalogPart1.GetWebPart(descriptions[0]);
closedWebPart.AllowClose = false;
}
}
// Use indexers to display the details of the CatalogPart controls.
Label1.Text = String.Empty;
Label1.Text =
"<h3>PageCatalogPart Details</h3>" +
"ID: " + myParts[0].ID + "<br />" +
"Count: " + myParts[0].GetAvailableWebPartDescriptions().Count;
Label1.Text +=
"<h3>DeclarativeCatalogPart Details</h3>" +
"ID: " + myParts["DeclarativeCatalogPart1"].ID + "<br />" +
"Count: " + myParts["DeclarativeCatalogPart1"].GetAvailableWebPartDescriptions().Count;
}
// </snippet2>
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>PageCatalogPart Details</title>
</head>
<body>
<form id="form1" runat="server">
<asp:WebPartManager ID="WebPartManager1" runat="server" />
<uc1:DisplayModeMenuCS ID="DisplayModeMenu1" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<asp:BulletedList
ID="BulletedList1"
Runat="server"
DisplayMode="HyperLink"
Title="Favorite Links" >
<asp:ListItem Value="http://msdn.microsoft.com">
MSDN
</asp:ListItem>
<asp:ListItem Value="http://www.asp.net">
ASP.NET
</asp:ListItem>
<asp:ListItem Value="http://www.msn.com">
MSN
</asp:ListItem>
</asp:BulletedList>
</ZoneTemplate>
</asp:WebPartZone>
<asp:CatalogZone ID="CatalogZone1" runat="server">
<ZoneTemplate>
<asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server">
<WebPartsTemplate>
<aspSample:TextDisplayWebPart runat="server"
id="TextDisplayWebPart1"
Title="Text Display WebPart" />
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>
<asp:PageCatalogPart ID="PageCatalogPart1" runat="server" />
</ZoneTemplate>
</asp:CatalogZone>
<hr />
<asp:Button ID="Button1"
runat="server"
Text="Display CatalogPart Properties"
OnClick="Button1_Click"/>
<br />
<asp:Label ID="Label1" runat="server" Text="" />
</form>
</body>
</html>
<%@ Page Language="vb" %>
<%@ register TagPrefix="uc1"
TagName="DisplayModeMenuVB"
Src="DisplayModeMenuVB.ascx" %>
<%@ 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">
<script runat="server">
' <snippet2>
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim list As New ArrayList(2)
list.Add(PageCatalogPart1)
list.Add(DeclarativeCatalogPart1)
' Pass an ICollection object to the constructor.
Dim myParts As New CatalogPartCollection(list)
Dim catalog As CatalogPart
For Each catalog In myParts
catalog.Description = "My " + catalog.DisplayTitle
Next catalog
' Use the IndexOf property to locate a CatalogPart control.
Dim PageCatalogPartIndex As Integer = _
myParts.IndexOf(PageCatalogPart1)
myParts(PageCatalogPartIndex).ChromeType = PartChromeType.TitleOnly
' Use the Contains method to see if a CatalogPart control exists.
If myParts.Contains(PageCatalogPart1) Then
Dim closedWebPart As WebPart = Nothing
Dim descriptions As WebPartDescriptionCollection = _
PageCatalogPart1.GetAvailableWebPartDescriptions()
If descriptions.Count > 0 Then
closedWebPart = PageCatalogPart1.GetWebPart(descriptions(0))
closedWebPart.AllowClose = False
End If
End If
' Use indexers to display the details of the CatalogPart controls.
Label1.Text = String.Empty
Label1.Text = _
"<h3>PageCatalogPart Details</h3>" & _
"ID: " & myParts(0).ID + "<br />" & _
"Count: " & myParts(0).GetAvailableWebPartDescriptions().Count
Label1.Text += _
"<h3>DeclarativeCatalogPart Details</h3>" & _
"ID: " & myParts("DeclarativeCatalogPart1").ID & "<br />" & _
"Count: " & myParts("DeclarativeCatalogPart1") _
.GetAvailableWebPartDescriptions().Count
End Sub
' </snippet2>
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>PageCatalogPart Details</title>
</head>
<body>
<form id="form1" runat="server">
<asp:WebPartManager ID="WebPartManager1" runat="server" />
<uc1:DisplayModeMenuVB ID="DisplayModeMenu1" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<asp:BulletedList
ID="BulletedList1"
Runat="server"
DisplayMode="HyperLink"
Title="Favorite Links" >
<asp:ListItem Value="http://msdn.microsoft.com">
MSDN
</asp:ListItem>
<asp:ListItem Value="http://www.asp.net">
ASP.NET
</asp:ListItem>
<asp:ListItem Value="http://www.msn.com">
MSN
</asp:ListItem>
</asp:BulletedList>
</ZoneTemplate>
</asp:WebPartZone>
<asp:CatalogZone ID="CatalogZone1" runat="server">
<ZoneTemplate>
<asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server">
<WebPartsTemplate>
<aspSample:TextDisplayWebPart runat="server"
id="TextDisplayWebPart1"
Title="Text Display WebPart" />
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>
<asp:PageCatalogPart ID="PageCatalogPart1" runat="server" />
</ZoneTemplate>
</asp:CatalogZone>
<hr />
<asp:Button ID="Button1"
runat="server"
Text="Display CatalogPart Properties"
OnClick="Button1_Click"/>
<br />
<asp:Label ID="Label1" runat="server" Text="" />
</form>
</body>
</html>
Ao carregar a página em um navegador, você pode alternar a página para o modo de catálogo selecionando Catálogo no controle de lista suspensa modo de exibição .When you load the page in a browser, you can switch the page into catalog mode by selecting Catalog in the Display Mode drop-down list control. Você pode adicionar o WebPart controle personalizado à página marcando a caixa de seleção ao lado dele e clicando em Adicionar.You can add the custom WebPart control to the page by selecting the check box next to it and clicking Add. Clique em fechar para retornar a página para o modo de procura.Click Close to return the page to browse mode. No controle que você acabou de adicionar, se você clicar no menu de verbos (a seta para baixo que aparece na barra de título) e, em seguida, clicar em fechar, o controle será removido da página e adicionado ao PageCatalogPart controle.On the control you just added, if you click the verbs menu (the down arrow that appears in the title bar) and then click Close, the control is removed from the page and added to the PageCatalogPart control. Retorne a página para o modo de catálogo e clique no link Catálogo de páginas para exibir o conteúdo do PageCatalogPart controle.Return the page to catalog mode, and click the Page Catalog link to view the contents of the PageCatalogPart control. Observe que o controle que você fechou agora aparece lá.Notice that the control you closed now appears there. Clicar no botão Exibir Propriedades de CatalogPart acessa o CatalogPartCollection objeto e exibe determinadas propriedades dos controles contidos CatalogPart .Clicking the Display CatalogPart Properties button accesses the CatalogPartCollection object and displays certain properties of the contained CatalogPart controls.
Comentários
A CatalogPartCollection classe é uma coleção somente leitura de CatalogPart controles, normalmente usada por uma CatalogZoneBase zona para controlar o conjunto de CatalogPart controles contidos na zona.The CatalogPartCollection class is a read-only collection of CatalogPart controls, typically used by a CatalogZoneBase zone to track the set of CatalogPart controls contained by the zone.
Quando uma página de Web Parts entra no modo de catálogo, a zona cria um novo CatalogPartCollection objeto que consiste nos CatalogPart controles.When a Web Parts page enters catalog mode, the zone creates a new CatalogPartCollection object consisting of the CatalogPart controls. Cada CatalogPart controle na coleção pode conter referências a zero ou mais controles de servidor Web, que são exibidos na forma de um catálogo de controles de servidor disponíveis.Each CatalogPart control in the collection can contain references to zero or more Web server controls, which are displayed in the form of a catalog of available server controls.
Você pode criar uma CatalogPartCollection coleção de controles para seu próprio uso programático se, por exemplo, você precisar executar alguma operação em massa em um conjunto de CatalogPart controles.You can create a CatalogPartCollection collection of controls for your own programmatic use if, for example, you need to perform some mass operation on a set of CatalogPart controls. Embora o CatalogPartCollection objeto seja somente leitura, você pode fazer alterações programáticas nos controles subjacentes referenciados na coleção.Even though the CatalogPartCollection object is read-only, you can make programmatic changes to the underlying controls referenced in the collection.
Construtores
| CatalogPartCollection() |
Inicializa uma nova instância vazia da classe CatalogPartCollection.Initializes a new, empty instance of the CatalogPartCollection class. |
| CatalogPartCollection(CatalogPartCollection, ICollection) |
Inicializa uma nova instância da classe CatalogPartCollection, passando uma coleção de ICollection dos controles de CatalogPart existentes em uma zona e uma coleção adicional de controles.Initializes a new instance of the CatalogPartCollection class by passing in an ICollection collection of the existing CatalogPart controls in a zone, and an additional collection of controls. |
| CatalogPartCollection(ICollection) |
Inicializa uma nova instância da classe CatalogPartCollection passando uma coleção de ICollection de controles de CatalogPart.Initializes a new instance of the CatalogPartCollection class by passing in an ICollection collection of CatalogPart controls. |
Campos
| Empty |
Faz referência a uma instância somente leitura estática vazia da coleção.References a static, read-only, empty instance of the collection. |
Propriedades
| Count |
Obtém o número de elementos contidos na instância de ReadOnlyCollectionBase.Gets the number of elements contained in the ReadOnlyCollectionBase instance. (Herdado de ReadOnlyCollectionBase) |
| InnerList |
Obtém a lista de elementos contidos na instância ReadOnlyCollectionBase.Gets the list of elements contained in the ReadOnlyCollectionBase instance. (Herdado de ReadOnlyCollectionBase) |
| Item[Int32] |
Obtém ou define um membro da coleção, com base em sua posição na coleção.Gets or sets a member of the collection, based on its position in the collection. |
| Item[String] |
Retorna um membro da coleção com base em um identificador de cadeia de caracteres exclusivo.Returns a member of the collection based on a unique string identifier. |
Métodos
| Contains(CatalogPart) |
Retorna um valor que indica se um determinado controle existe na coleção.Returns a value indicating whether a particular control exists in the collection. |
| CopyTo(CatalogPart[], Int32) |
Copia a coleção para uma matriz de objetos de CatalogPart.Copies the collection to an array of CatalogPart objects. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetEnumerator() |
Retorna um enumerador que itera pela instância ReadOnlyCollectionBase.Returns an enumerator that iterates through the ReadOnlyCollectionBase instance. (Herdado de ReadOnlyCollectionBase) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| IndexOf(CatalogPart) |
Retorna a posição de um membro específico da coleção.Returns the position of a particular member of the collection. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| ICollection.CopyTo(Array, Int32) |
Copia todo o ReadOnlyCollectionBase em um Array unidimensional compatível, começando no índice especificado da matriz de destino.Copies the entire ReadOnlyCollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array. (Herdado de ReadOnlyCollectionBase) |
| ICollection.IsSynchronized |
Obtém um valor que indica se o acesso a um objeto ReadOnlyCollectionBase é sincronizado (thread-safe).Gets a value indicating whether access to a ReadOnlyCollectionBase object is synchronized (thread safe). (Herdado de ReadOnlyCollectionBase) |
| ICollection.SyncRoot |
Obtém um objeto que pode ser usado para sincronizar o acesso a um objeto ReadOnlyCollectionBase.Gets an object that can be used to synchronize access to a ReadOnlyCollectionBase object. (Herdado de ReadOnlyCollectionBase) |
Métodos de Extensão
| Cast<TResult>(IEnumerable) |
Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type. |
| OfType<TResult>(IEnumerable) |
Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type. |
| AsParallel(IEnumerable) |
Habilita a paralelização de uma consulta.Enables parallelization of a query. |
| AsQueryable(IEnumerable) |
Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable. |