DesignerSerializationVisibilityAttribute Classe

Definição

Especifica o tipo de persistência a usar ao serializar uma propriedade num componente em tempo de conceção.

public ref class DesignerSerializationVisibilityAttribute sealed : 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)]
public sealed class DesignerSerializationVisibilityAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property)>]
type DesignerSerializationVisibilityAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)>]
type DesignerSerializationVisibilityAttribute = class
    inherit Attribute
Public NotInheritable Class DesignerSerializationVisibilityAttribute
Inherits Attribute
Herança
DesignerSerializationVisibilityAttribute
Atributos

Exemplos

O exemplo de código seguinte demonstra o uso de um DesignerSerializationVisibilityAttribute conjunto de .Content Persiste os valores de uma propriedade pública de um controlo de utilizador, que pode ser configurado no momento do design. Para usar o exemplo, compila primeiro o código seguinte numa biblioteca de controlo do utilizador. De seguida, adicione uma referência ao ficheiro de .dll compilado num novo projeto Windows Application. Se estiver a usar Visual Studio, o ContentSerializationExampleControl é automaticamente adicionado ao Toolbox.

Arraste o controlo do Toolbox para um formulário e define as propriedades do objeto DimensionData listadas no janela Propriedades. Quando visualiza o código do formulário, o código terá sido adicionado ao InitializeComponent método do formulário pai. Este código define os valores das propriedades do controlo para aqueles que definiu no modo de design.

#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

Observações

Quando um serializador persiste o estado persistente de um documento em modo de design, frequentemente adiciona código ao método de inicialização dos componentes para persistir valores de propriedades definidas em tempo de projeto. Isto acontece por defeito para a maioria dos tipos básicos, se nenhum atributo tiver sido definido para direcionar outro comportamento.

Com o DesignerSerializationVisibilityAttribute, pode indicar se o valor de uma propriedade é Visible, e deve ser persistido no código de inicialização, Hidden, e não deve persistir no código de inicialização, ou consiste em Content, que deve ter código de inicialização gerado para cada propriedade pública, não propriedade oculta do objeto atribuído à propriedade.

Os membros que não têm um DesignerSerializationVisibilityAttribute testamento são tratados como se tivessem um DesignerSerializationVisibilityAttribute valor de Visible. Os valores de uma propriedade marcada como Visible serão serializados, se possível, por um serializador para o tipo. Para especificar serialização personalizada para um tipo ou propriedade particular, use o DesignerSerializerAttribute.

Para obter mais informações, consulte Atributos.

Construtores

Name Description
DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility)

Inicializa uma nova instância da DesignerSerializationVisibilityAttribute classe usando o valor especificado DesignerSerializationVisibility .

Campos

Name Description
Content

Especifica que um serializador deve serializar o conteúdo da propriedade, em vez da propriedade em si. Este campo é só de leitura.

Default

Especifica o valor padrão, que é Visible, ou seja, um designer visual usa regras padrão para gerar o valor de uma propriedade. Este static campo é só de leitura.

Hidden

Especifica que um serializador não deve serializar o valor da propriedade. Este static campo é só de leitura.

Visible

Especifica que um serializador deve poder serializar o valor da propriedade. Este static campo é só de leitura.

Propriedades

Name Description
TypeId

Quando implementado numa classe derivada, obtém um identificador único para esta Attribute.

(Herdado de Attribute)
Visibility

Obtém um valor que indica o modo básico de serialização que um serializador deve usar ao determinar se e como persistir o valor de uma propriedade.

Métodos

Name Description
Equals(Object)

Indica se esta instância e um objeto especificado são iguais.

GetHashCode()

Devolve o código de hash deste objeto.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Recebe um valor que indica se o valor atual do atributo é o valor padrão do atributo.

Match(Object)

Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho.

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

Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1).

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

Proporciona acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Ver também