Compartir a través de


DesignerSerializationVisibilityAttribute Clase

Definición

Especifica el tipo de persistencia que se va a usar al serializar una propiedad en un componente en tiempo de diseño.

public ref class DesignerSerializationVisibilityAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)]
public sealed class DesignerSerializationVisibilityAttribute : Attribute
public sealed class DesignerSerializationVisibilityAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property)]
public sealed class DesignerSerializationVisibilityAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)>]
type DesignerSerializationVisibilityAttribute = class
    inherit Attribute
type DesignerSerializationVisibilityAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property)>]
type DesignerSerializationVisibilityAttribute = class
    inherit Attribute
Public NotInheritable Class DesignerSerializationVisibilityAttribute
Inherits Attribute
Herencia
DesignerSerializationVisibilityAttribute
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra el uso de un DesignerSerializationVisibilityAttribute conjunto en Content. Conserva los valores de una propiedad pública de un control de usuario, que se puede configurar en tiempo de diseño. Para usar el ejemplo, compile primero el código siguiente en una biblioteca de control de usuario. A continuación, agregue una referencia al archivo .dll compilado en un nuevo proyecto de aplicación de Windows. Si usa Visual Studio, el ContentSerializationExampleControl se agrega automáticamente al Toolbox.

Arrastre el control desde el Toolbox a un formulario y establezca las propiedades del objeto /> InitializeComponent método del formulario primario. Este código establece los valores de las propiedades del control en los que se han establecido en modo de diseño.

#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.ComponentModel;
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 : UserControl
{
    Container components;

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public DimensionData Dimensions => new(this);

    public ContentSerializationExampleControl() => InitializeComponent();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            components?.Dispose();
        }
        base.Dispose(disposing);
    }

    void InitializeComponent() => components = new Container();
}

[TypeConverter(typeof(ExpandableObjectConverter))]
// This attribute indicates that the public properties of this object should be listed in the property grid.
public class DimensionData
{
    readonly 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 => owner.Location;
        set => owner.Location = value;
    }

    public Size FormSize
    {
        get => owner.Size;
        set => owner.Size = value;
    }
}
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


        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


        Private Sub InitializeComponent()
        End Sub
    End Class

    ' 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


        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
End Namespace 'DesignerSerializationVisibilityTest

Comentarios

Cuando un serializador conserva el estado persistente de un documento de modo de diseño, a menudo agrega código al método de inicialización de componentes para conservar los valores de las propiedades que se han establecido en tiempo de diseño. Esto sucede de forma predeterminada para la mayoría de los tipos básicos, si no se ha establecido ningún atributo para dirigir otro comportamiento.

DesignerSerializationVisibilityAttributeCon , puede indicar si el valor de una propiedad es Visible, y debe conservarse en el código de inicialización, Hidden, y no debe conservarse en el código de inicialización, o consta de , que debe tener código de Contentinicialización generado para cada propiedad pública, no oculta del objeto asignado a la propiedad .

Los miembros que no tienen un DesignerSerializationVisibilityAttribute se tratarán como si tuvieran un DesignerSerializationVisibilityAttribute con un valor de Visible. Los valores de una propiedad marcada como Visible se serializarán, si es posible, mediante un serializador para el tipo. Para especificar la serialización personalizada para un tipo o propiedad determinado, use .DesignerSerializerAttribute

Para obtener más información, consulte Attributes (Atributos).

Constructores

Nombre Description
DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility)

Inicializa una nueva instancia de la DesignerSerializationVisibilityAttribute clase utilizando el valor especificado DesignerSerializationVisibility .

Campos

Nombre Description
Content

Especifica que un serializador debe serializar el contenido de la propiedad, en lugar de la propia propiedad. Este campo es de solo lectura.

Default

Especifica el valor predeterminado, que es Visible, es decir, un diseñador visual usa reglas predeterminadas para generar el valor de una propiedad. Este static campo es de solo lectura.

Hidden

Especifica que un serializador no debe serializar el valor de la propiedad . Este static campo es de solo lectura.

Visible

Especifica que se debe permitir que un serializador serialice el valor de la propiedad . Este static campo es de solo lectura.

Propiedades

Nombre Description
TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.

(Heredado de Attribute)
Visibility

Obtiene un valor que indica el modo de serialización básico que debe usar un serializador al determinar si y cómo conservar el valor de una propiedad.

Métodos

Nombre Description
Equals(Object)

Indica si esta instancia y un objeto especificado son iguales.

GetHashCode()

Devuelve el código hash de este objeto.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsDefaultAttribute()

Obtiene un valor que indica si el valor actual del atributo es el valor predeterminado del atributo.

Match(Object)

Cuando se reemplaza en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

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

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

(Heredado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera la información de tipo de un objeto, que se puede usar para obtener la información de tipo de una interfaz.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

(Heredado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a propiedades y métodos expuestos por un objeto .

(Heredado de Attribute)

Se aplica a

Consulte también