DesignerSerializationVisibilityAttribute Class

Definición

Especifica el tipo de persistencia que se va a utilizar al serializar una propiedad en un componente en tiempo de diseño. Specifies the type of persistence to use when serializing a property on a component at design time.

[System.AttributeUsage(System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)]
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property)]
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Field | System.AttributeTargets.Event)]
public sealed class DesignerSerializationVisibilityAttribute : Attribute
Herencia
DesignerSerializationVisibilityAttribute
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra el uso de un DesignerSerializationVisibilityAttribute establecido en Content.The following code example demonstrates the use of a DesignerSerializationVisibilityAttribute set to Content. Conserva los valores de una propiedad pública de un control de usuario que se puede configurar en tiempo de diseño.It persists the values of a public property of a user control, which can be configured at design time. Para usar el ejemplo, primero compile el código siguiente en una biblioteca de controles de usuario.To use the example, first compile the following code into a user control library. A continuación, agregue una referencia al archivo .dll compilado en un nuevo proyecto de aplicación de Windows.Next, add a reference to the compiled .dll file in a new Windows Application project. Si usa Visual Studio, el ContentSerializationExampleControl se agrega automáticamente a la cuadro de herramientas.If you are using Visual Studio, the ContentSerializationExampleControl is automatically added to the Toolbox.

Arrastre el control desde el cuadro de herramientas a un formulario y establecer las propiedades de la DimensionData objeto aparece en la ventana Propiedades.Drag the control from the Toolbox to a form, and set the properties of the DimensionData object listed in the Properties window. Al ver el código del formulario, se habrá agregado código para el InitializeComponent método del formulario primario.When you view the code for the form, code will have been added to the InitializeComponent method of the parent form. Este código establece los valores de las propiedades del control a las que se ha establecido en modo de diseño.This code sets the values of the control's properties to those which you have set in design mode.

#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Drawing;
using namespace System::Windows::Forms;

// This attribute indicates that the public properties of this object should be listed in the property grid.

[TypeConverterAttribute(System::ComponentModel::ExpandableObjectConverter::typeid)]
public ref class DimensionData
{
private:
   Control^ owner;

internal:

   // This class reads and writes the Location and Size properties from the Control which it is initialized to.
   DimensionData( Control^ owner )
   {
      this->owner = owner;
   }

public:

   property Point Location 
   {
      Point get()
      {
         return owner->Location;
      }

      void set( Point value )
      {
         owner->Location = value;
      }

   }

   property Size FormSize 
   {
      Size get()
      {
         return owner->Size;
      }

      void set( Size value )
      {
         owner->Size = value;
      }
   }
};

// The code for this user control declares a public property of type DimensionData with a DesignerSerializationVisibility 
// attribute set to DesignerSerializationVisibility.Content, indicating that the properties of the object should be serialized.
// The public, not hidden properties of the object that are set at design time will be persisted in the initialization code
// for the class object. Content persistence will not work for structs without a custom TypeConverter.  
public ref class ContentSerializationExampleControl: public System::Windows::Forms::UserControl
{
private:
   System::ComponentModel::Container^ components;

public:

   property DimensionData^ Dimensions 
   {
      [DesignerSerializationVisibility(DesignerSerializationVisibility::Content)]
      DimensionData^ get()
      {
         return gcnew DimensionData( this );
      }
   }
   ContentSerializationExampleControl()
   {
      InitializeComponent();
   }

public:
   ~ContentSerializationExampleControl()
   {
      if ( components != nullptr )
      {
         delete components;
      }
   }

private:
   void InitializeComponent()
   {
      components = gcnew System::ComponentModel::Container;
   }
};
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;

namespace DesignerSerializationVisibilityTest
{
    // The code for this user control declares a public property of type DimensionData with a DesignerSerializationVisibility 
    // attribute set to DesignerSerializationVisibility.Content, indicating that the properties of the object should be serialized.

    // The public, not hidden properties of the object that are set at design time will be persisted in the initialization code
    // for the class object. Content persistence will not work for structs without a custom TypeConverter.		

    public class ContentSerializationExampleControl : System.Windows.Forms.UserControl
    {
	private System.ComponentModel.Container components = null;				
	
	[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
	public DimensionData Dimensions
	{
	    get 
	    {
		return new DimensionData(this);
	    }		
	}

	public ContentSerializationExampleControl()
	{
    	    InitializeComponent();		
	}
		
	protected override void Dispose( bool disposing )
	{
	    if( disposing )
	    {
		if( components != null )
		    components.Dispose();
	    }
	    base.Dispose( disposing );
	}

	private void InitializeComponent()
	{
	    components = new System.ComponentModel.Container();
	}
    }

    [TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
    // This attribute indicates that the public properties of this object should be listed in the property grid.
    public class DimensionData
    {		
	private Control owner;

	// This class reads and writes the Location and Size properties from the Control which it is initialized to.
	internal DimensionData(Control owner)
	{
    	    this.owner = owner;			
	}

	public Point Location
	{
	    get
	    {
		return owner.Location;
	    }
	    set
	    {
		owner.Location = value;
	    }
	}

	public Size FormSize
	{
	    get
    	    {
		return owner.Size;
	    }
	    set
	    {
		owner.Size = value;
	    }
	}
    }
}
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing
Imports System.Windows.Forms

Namespace DesignerSerializationVisibilityTest
    _
    ' The code for this user control declares a public property of type DimensionData with a DesignerSerializationVisibility 
    ' attribute set to DesignerSerializationVisibility.Content, indicating that the properties of the object should be serialized.

    ' The public, not hidden properties of the object that are set at design time will be persisted in the initialization code
    ' for the class object. Content persistence will not work for structs without a custom TypeConverter.		
    Public Class ContentSerializationExampleControl
        Inherits System.Windows.Forms.UserControl
        Private components As System.ComponentModel.Container = Nothing


        <DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
        Public ReadOnly Property Dimensions() As DimensionData
            Get
                Return New DimensionData(Me)
            End Get
        End Property


        Public Sub New()
            InitializeComponent()
        End Sub 'New


        Protected Overloads Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If (components IsNot Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub 'Dispose


        Private Sub InitializeComponent()
        End Sub 'InitializeComponent
    End Class 'ContentSerializationExampleControl

    ' This attribute indicates that the public properties of this object should be listed in the property grid.
   <TypeConverterAttribute(GetType(System.ComponentModel.ExpandableObjectConverter))> _   
    Public Class DimensionData
        Private owner As Control

        ' This class reads and writes the Location and Size properties from the Control which it is initialized to.
        Friend Sub New(ByVal owner As Control)
            Me.owner = owner
        End Sub 'New


        Public Property Location() As Point
            Get
                Return owner.Location
            End Get
            Set(ByVal Value As Point)
                owner.Location = Value
            End Set
        End Property


        Public Property FormSize() As Size
            Get
                Return owner.Size
            End Get
            Set(ByVal Value As Size)
                owner.Size = Value
            End Set
        End Property
    End Class 'DimensionData
End Namespace 'DesignerSerializationVisibilityTest

Comentarios

Cuando un serializador conserva el estado con persistencia de un documento en modo de diseño, suele agregar código al método de inicialización de componentes para conservar los valores de propiedades que se han establecido en tiempo de diseño.When a serializer persists the persistable state of a design mode document, it often adds code to the initialization method of components to persist values of properties that have been set at design time. Esto sucede de forma predeterminada para los tipos más básicos, si no se ha establecido ningún atributo para dirigir el otro comportamiento.This happens by default for most basic types, if no attribute has been set to direct other behavior.

Con el DesignerSerializationVisibilityAttribute, puede indicar si el valor de una propiedad es Visibley deben almacenarse en el código de inicialización, Hiddeny no debe conservarse en el código de inicialización o consta de Content, que debería tener código de inicialización generado para cada propiedad pública, no oculta del objeto asignado a la propiedad.With the DesignerSerializationVisibilityAttribute, you can indicate whether the value for a property is Visible, and should be persisted in initialization code, Hidden, and should not be persisted in initialization code, or consists of Content, which should have initialization code generated for each public, not hidden property of the object assigned to the property.

Los miembros que no tienen un DesignerSerializationVisibilityAttribute se tratará como si tuvieran un DesignerSerializationVisibilityAttribute con un valor de Visible.Members that do not have a DesignerSerializationVisibilityAttribute will be treated as though they have a DesignerSerializationVisibilityAttribute with a value of Visible. Los valores de una propiedad marcan como Visible se va a serializar, si es posible, un serializador para el tipo.The values of a property marked as Visible will be serialized, if possible, by a serializer for the type. Para especificar la serialización personalizada para un tipo determinado o una propiedad, utilice el DesignerSerializerAttribute.To specify custom serialization for a particular type or property, use the DesignerSerializerAttribute.

Para obtener más información, consulte Attributes (Atributos).For more information, see Attributes.

Constructores

DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility)

Inicializa una nueva instancia de la clase DesignerSerializationVisibilityAttribute mediante el valor especificado de DesignerSerializationVisibility. Initializes a new instance of the DesignerSerializationVisibilityAttribute class using the specified DesignerSerializationVisibility value.

Campos

Content

Especifica que un serializador debe serializar el contenido de la propiedad en lugar de la propiedad. Specifies that a serializer should serialize the contents of the property, rather than the property itself. Este campo es de solo lectura. This field is read-only.

Default

Especifica el valor predeterminado, que es Visible, es decir, un diseñador visual utiliza las reglas predeterminadas para generar el valor de una propiedad. Specifies the default value, which is Visible, that is, a visual designer uses default rules to generate the value of a property. Este campo static es de solo lectura. This static field is read-only.

Hidden

Especifica que un serializador no debe serializar el valor de la propiedad. Specifies that a serializer should not serialize the value of the property. Este campo static es de solo lectura. This static field is read-only.

Visible

Especifica que se debe permitir a un serializador la serialización del valor de la propiedad. Specifies that a serializer should be allowed to serialize the value of the property. Este campo static es de solo lectura. This static field is read-only.

Propiedades

TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute. When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)
Visibility

Obtiene un valor que indica el modo básico de serialización que debe utilizar un serializador al determinar si se conserva el valor de una propiedad y la forma de hacerlo. Gets a value indicating the basic serialization mode a serializer should use when determining whether and how to persist the value of a property.

Métodos

Equals(Object)

Indica si esta instancia y un objeto especificado son iguales. Indicates whether this instance and a specified object are equal.

GetHashCode()

Devuelve el código hash de este objeto. Returns the hash code for this object.

GetType()

Obtiene el Type de la instancia actual. Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute()

Obtiene un valor que indica si el valor actual del atributo es su valor predeterminado. Gets a value indicating whether the current value of the attribute is the default value for the attribute.

Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado. When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone()

Crea una copia superficial del Object actual. Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Devuelve una cadena que representa el objeto actual. Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

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

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío. Maps a set of names to a corresponding set of dispatch identifiers.

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

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz. 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)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 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)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto. Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Se aplica a

Consultar también