PersistChildrenAttribute PersistChildrenAttribute PersistChildrenAttribute PersistChildrenAttribute Class

Definizione

Definisce un attributo utilizzato dai controlli server ASP.NET per indicare in fase di progettazione se il contenuto annidato incluso in un controllo server corrisponde a controlli o a proprietà del controllo server.Defines an attribute that is used by ASP.NET server controls to indicate at design time whether nested content that is contained within a server control corresponds to controls or to properties of the server control. Questa classe non può essere ereditata.This class cannot be inherited.

public ref class PersistChildrenAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class)]
public sealed class PersistChildrenAttribute : Attribute
type PersistChildrenAttribute = class
    inherit Attribute
Public NotInheritable Class PersistChildrenAttribute
Inherits Attribute
Ereditarietà
PersistChildrenAttributePersistChildrenAttributePersistChildrenAttributePersistChildrenAttribute
Attributi

Esempi

L'esempio di codice in questa sezione contiene due parti.The code example in this section contains two parts. Il primo esempio di codice viene illustrato come impostare i metadati di un controllo personalizzato in modo che in fase di progettazione, il contenuto annidato viene mantenuto come proprietà del controllo.The first code example demonstrates how to set the metadata of a custom control so that at design time, its nested content is persisted as properties of the control. Il secondo esempio di codice viene illustrato come usare le classi in una pagina ASP.NET.The second code example demonstrates how to use classes in an ASP.NET page.

Esempio di codice seguente viene illustrato come applicare il PersistChildrenAttribute attributo in modo che nessuno dei controlli annidati di un controllo server personalizzato venga mantenuto come controlli nidificati.The following code example demonstrates how to apply the PersistChildrenAttribute attribute so that none of a custom server control's nested controls are persisted as nested controls. Il controllo server personalizzato denominato CollectionPropertyControl ha il PersistChildrenAttribute attributo impostato su false in modo che il Employee vengono mantenuti gli oggetti che vengono aggiunti come elementi annidati.The custom server control named CollectionPropertyControl has the PersistChildrenAttribute attribute set to false so that the Employee objects that are added are persisted as nested elements.

using System;
using System.Collections;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;

namespace PersistChildrenSamples
{
   // The child element class.
   [AspNetHostingPermission(SecurityAction.Demand, 
      Level=AspNetHostingPermissionLevel.Minimal)]
   public sealed class Employee
   {
      private String name;
      private String title;
      private String alias;

      public Employee():this ("","",""){}
      
      public Employee (String name, String title, String alias)
      {
         this.name = name;
         this.title = title;
         this.alias = alias;
      }
      public String Name
      {
         get
         {
            return name;
         }
         set
         {
            name = value;
         }
      }
      
      public String Title
      {
         get
         {
            return title;
         }
         set
         {
            title = value;
         }
      }
      
      public String Alias
      {
         get
         {
            return alias;
         }
         set
         {
            alias = value;
         }
      }
   }
   // Use the PersistChildren attribute to set the Persist
   // property to false so that none of this class's
   // child controls will be persisted as controls. They will
   // be persisted only as child elements of this class.
   // If you set the PersistChildren attribute to true, or if you
   // do not include this attribute when you create a control,
   // the child controls will be persisted as controls.   
   [PersistChildren(false)]
   [AspNetHostingPermission(SecurityAction.Demand, 
      Level=AspNetHostingPermissionLevel.Minimal)]
   public sealed class CollectionPropertyControl : Control
   {  
      private String header;
      private ArrayList employees = new ArrayList();
      
      public String Header
      {
         get
         {
            return header;
         }
         set
         {
            header = value;
         }
      }


      
      public ArrayList Employees
      {
         get 
         {
            return employees;
         }
      }
      // Override the CreateChildControls method to 
      // add child controls to the Employees property when this
      // custom control is requested from a page.
      protected override void CreateChildControls()
      {
         Label label = new Label();
         label.Text = Header;
         label.BackColor = Color.Beige;
         label.ForeColor = Color.Red;
         Controls.Add(label);
         Controls.Add(new LiteralControl("<BR> <BR>"));

         Table table = new Table();
         TableRow htr = new TableRow();

         TableHeaderCell hcell1 = new TableHeaderCell();    
         hcell1.Text = "Name";
         htr.Cells.Add(hcell1);

         TableHeaderCell hcell2 = new TableHeaderCell();
         hcell2.Text = "Title";
         htr.Cells.Add(hcell2);
         
         TableHeaderCell hcell3 = new TableHeaderCell();
         hcell3.Text = "Alias";
         htr.Cells.Add(hcell3);
         table.Rows.Add(htr);

         table.BorderWidth = 2;
         table.BackColor = Color.Beige;
         table.ForeColor = Color.Red;
         foreach (Employee employee in Employees)
         {
            TableRow tr = new TableRow();

            TableCell cell1 = new TableCell();
            cell1.Text = employee.Name;
            tr.Cells.Add(cell1);
            
            TableCell cell2 = new TableCell();
            cell2.Text = employee.Title;
            tr.Cells.Add(cell2);
            
            TableCell cell3 = new TableCell();
            cell3.Text = employee.Alias;
            tr.Cells.Add(cell3);
            
            table.Rows.Add(tr);
         }
         Controls.Add(table);
         
      }
   }
}
' Create a namespace that defines two classes, one a custom control, Employee,
' which is created for every instance of a child element with its name
' declared in a page associated with this namespace, the other, Employees,
' which contains these child elements.
Imports System
Imports System.Collections
Imports System.Drawing
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Security.Permissions

Namespace PersistChildrenSampleVB

' Create a class that will be rendered as a child of the control
' that has the ParseChildren attribute applied to it.
 <AspNetHostingPermission(SecurityAction.Demand, _
   Level:=AspNetHostingPermissionLevel.Minimal)> _
 Public NotInheritable Class Employee
   Private _name As String
   Private _title As String
   Private _alias As String
   
   
   Public Sub New()
      Me.New("", "", "")
   End Sub 'New

    
   Public Sub New(name As String, title As String, employeeAlias As String)
      Me._name = name
      Me._title = title
      Me._alias = employeeAlias
   End Sub 'New
   
   Public Property Name() As String
      Get
         Return _name
      End Get
      Set
         _name = value
      End Set
   End Property
   
   
   Public Property Title() As String
      Get
         Return _title
      End Get
      Set
         _title = value
      End Set
   End Property
   
   
   Public Property [Alias]() As String
      Get
         Return _alias
      End Get
      Set
         _alias = value
      End Set
   End Property
End Class 'Employee

 ' Use the PersistChildren attribute to set the Persist
 ' property to false so that none of this class's
 ' child controls will be persisted as controls. They will
 ' be persisted only as child elements of this class.
 ' If you set the PersistChildren attribute to true, or if you
 ' do not include this attribute when you create a control,
 ' the child controls will be persisted as controls.
 <PersistChildren(False)>  _
 <AspNetHostingPermission(SecurityAction.Demand, _
   Level:=AspNetHostingPermissionLevel.Minimal)> _
 Public NotInheritable Class CollectionPropertyControl
   Inherits Control
   Private _header As String
   Private _employees As New ArrayList()
   
   
   Public Property Header() As String
      Get
         Return _header
      End Get
      Set
         _header = value
      End Set
   End Property
   
   
   
   
   Public ReadOnly Property Employees() As ArrayList
      Get
         Return _employees
      End Get
   End Property
   
   ' Override the CreateChildControls method to 
   ' add child controls to the Employees property when this
   ' custom control is requested from a page.
   Protected Overrides Sub CreateChildControls()
      Dim label As New Label()
      label.Text = Header
      label.BackColor = Color.Beige
      label.ForeColor = Color.Red
      Controls.Add(label)
      Controls.Add(New LiteralControl("<BR> <BR>"))
      
      Dim table As New Table()
      Dim htr As New TableRow()
      
      Dim hcell1 As New TableHeaderCell()
      hcell1.Text = "Name"
      htr.Cells.Add(hcell1)
      
      Dim hcell2 As New TableHeaderCell()
      hcell2.Text = "Title"
      htr.Cells.Add(hcell2)
      
      Dim hcell3 As New TableHeaderCell()
      hcell3.Text = "Alias"
      htr.Cells.Add(hcell3)
      table.Rows.Add(htr)
      
      table.BorderWidth = Unit.Pixel(2)
      table.BackColor = Color.Beige
      table.ForeColor = Color.Red
      Dim employee As Employee
      For Each employee In  Employees
         Dim tr As New TableRow()
         
         Dim cell1 As New TableCell()
         cell1.Text = employee.Name
         tr.Cells.Add(cell1)
         
         Dim cell2 As New TableCell()
         cell2.Text = employee.Title
         tr.Cells.Add(cell2)
         
         Dim cell3 As New TableCell()
         cell3.Text = employee.Alias
         tr.Cells.Add(cell3)
         
         table.Rows.Add(tr)
      Next employee
      Controls.Add(table)
   End Sub 'CreateChildControls 
 End Class 'CollectionPropertyControl
End Namespace ' PersistChildrenSampleVB

Esempio di codice seguente viene illustrato come utilizzare il CollectionPropertyControl e Employee classi in una pagina ASP.NET.The following code example demonstrates how to use the CollectionPropertyControl and Employee classes in an ASP.NET page.

<%@ Page Language="C#" %>
<%@ Register TagPrefix="AspSample" Assembly="Samples.AspNet.CS.Controls" Namespace="PersistChildrenSamples" %>

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

<script runat="server">
  
  protected void Page_Load(object sender, EventArgs e)
  {

    // Create two new employees and add them to the custom control.
    Employee e1 = new Employee("Employee 1", "Title 1", "Alias 1");
    Employee e2 = new Employee("Employee 2", "Title 2", "Alias 2");
    CollectionPropertyControl1.Employees.Add(e1);
    CollectionPropertyControl1.Employees.Add(e2);

    // Verify attribute values.
    PersistChildrenAttribute p =
      (PersistChildrenAttribute)Attribute.GetCustomAttribute(typeof(CollectionPropertyControl), 
      typeof(PersistChildrenAttribute));

    StringBuilder sb = new StringBuilder();
    sb.Append("The Persist property is " + p.Persist.ToString() + "<br />");
    sb.Append("The UseCustomPersistence property is " + p.UsesCustomPersistence.ToString() + "<br />");
    sb.Append("The IsDefault method returns " + p.IsDefaultAttribute().ToString());
    Message.Text = sb.ToString();
    
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>PersistChildrenAttribute</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="Message"
                 runat="server"/>
      <AspSample:CollectionPropertyControl id="CollectionPropertyControl1" 
                                           runat="server">
      </AspSample:CollectionPropertyControl>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register TagPrefix="AspSample" Assembly="Samples.AspNet.VB.Controls" Namespace="PersistChildrenSampleVB" %>


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

<script runat="server">
  
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    ' Create two new employees and add them to the custom control.
    Dim e1 As New Employee("Employee 1", "Title 1", "Alias 1")
    Dim e2 As New Employee("Employee 2", "Title 2", "Alias 2")
    CollectionPropertyControl1.Employees.Add(e1)
    CollectionPropertyControl1.Employees.Add(e2)

    ' Verify attribute values.
    Dim p As PersistChildrenAttribute = _
    Attribute.GetCustomAttribute(GetType(CollectionPropertyControl), _
    GetType(PersistChildrenAttribute))

    Dim sb As New StringBuilder()
    sb.Append("The Persist property is " & p.Persist.ToString() & "<br />")
    sb.Append("The UseCustomPersistence property is " & p.UsesCustomPersistence.ToString() & "<br />")
    sb.Append("The IsDefault method returns " & p.IsDefaultAttribute().ToString())
    Message.Text = sb.ToString()

  End Sub
  
</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>PersistChildrenAttribute</title>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
      <asp:Label ID="Message"
                 runat="server"/>
      <AspSample:CollectionPropertyControl id="CollectionPropertyControl1" 
                                           runat="server">
      </AspSample:CollectionPropertyControl>
    </div>
    </form>
</body>
</html>

Commenti

Il PersistChildrenAttribute viene usato in combinazione con il ParseChildrenAttribute per determinare il contenuto annidato come di un controllo viene interpretato.The PersistChildrenAttribute is used in combination with the ParseChildrenAttribute to determine how nested content of a control is interpreted. Se PersistChildrenAttribute viene true e ParseChildrenAttribute è false, il contenuto annidato incluso all'interno di un controllo server ASP.NET viene mantenuto come controlli.If PersistChildrenAttribute is true and ParseChildrenAttribute is false, the nested content contained within an ASP.NET server control is persisted as controls. Se PersistChildrenAttribute viene false e ParseChildrenAttribute è true, il contenuto annidato viene mantenuto come proprietà del controllo server.If PersistChildrenAttribute is false and ParseChildrenAttribute is true, the nested content is persisted as properties of the server control. Per altre informazioni sull'utilizzo di attributi, vedere attributi.For more information about using attributes, see Attributes.

Costruttori

PersistChildrenAttribute(Boolean) PersistChildrenAttribute(Boolean) PersistChildrenAttribute(Boolean) PersistChildrenAttribute(Boolean)

Inizializza una nuova istanza della classe PersistChildrenAttribute utilizzando un valore Boolean che indica se mantenere il contenuto annidato come controlli nidificati.Initializes a new instance of the PersistChildrenAttribute class using a Boolean value indicating whether to persist nested content as nested controls.

PersistChildrenAttribute(Boolean, Boolean) PersistChildrenAttribute(Boolean, Boolean) PersistChildrenAttribute(Boolean, Boolean) PersistChildrenAttribute(Boolean, Boolean)

Inizializza una nuova istanza della classe PersistChildrenAttribute utilizzando due valori Boolean.Initializes a new instance of the PersistChildrenAttribute class using two Boolean values. Uno dei valori indica se mantenere il contenuto annidato come controlli nidificati e l'altro indica se utilizzare un metodo di persistenza personalizzato.One indicating whether to persist nested content as nested controls and the other indicating whether to use a custom persistence method.

Campi

Default Default Default Default

Indica lo stato predefinito dell'attributo.Indicates the default attribute state. Il campo Default è in sola lettura.The Default field is read-only.

No No No No

Indica che il contenuto annidato non deve essere mantenuto come controlli nidificati in fase di progettazione.Indicates that nested content should not persist as nested controls at design time. Questo campo è di sola lettura.This field is read-only.

Yes Yes Yes Yes

Indica che il contenuto annidato deve essere mantenuto come controlli in fase di progettazione.Indicates that nested content should persist as controls at design time. Il campo Yes è in sola lettura.The Yes field is read-only.

Proprietà

Persist Persist Persist Persist

Ottiene un valore che indica se il contenuto annidato viene mantenuto come controlli annidati in fase di progettazione.Gets a value that indicates whether the nested content is persisted as nested controls at design time.

TypeId TypeId TypeId TypeId

Quando è implementata in una classe derivata, ottiene un identificatore univoco della classe Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)
UsesCustomPersistence UsesCustomPersistence UsesCustomPersistence UsesCustomPersistence

Ottiene un valore che indica se il controllo server fornisce la persistenza dei controlli annidati in fase di progettazione.Gets a value indicating whether the server control provides custom persistence of nested controls at design time.

Metodi

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Viene utilizzato come funzione hash per la classe PersistChildrenAttribute.Serves as a hash function for the PersistChildrenAttribute class.

GetType() GetType() GetType() GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

Restituisce un valore che indica se il valore dell'istanza corrente della classe PersistChildrenAttribute è il valore predefinito della classe derivata.Returns a value indicating whether the value of the current instance of the PersistChildrenAttribute class is the default value of the derived class.

Match(Object) Match(Object) Match(Object) Match(Object)

Quando è sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza equivale a un oggetto specificato.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object.

(Inherited from Object)

Implementazioni dell'interfaccia esplicita

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo relative a un oggetto, che possono essere usate per ottenere informazioni sul tipo relative a un'interfaccia.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso a proprietà e metodi esposti da un oggetto.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Si applica a

Vedi anche