Compartilhar via


DesignerSerializationVisibilityAttribute Classe

Definição

Especifica o tipo de persistência a ser usado ao serializar uma propriedade em um componente em tempo de design.

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
Herança
DesignerSerializationVisibilityAttribute
Atributos

Exemplos

O exemplo de código a seguir demonstra o uso de um DesignerSerializationVisibilityAttribute conjunto para Content. Ele persiste os valores de uma propriedade pública de um controle de usuário, que pode ser configurado em tempo de design. Para usar o exemplo, primeiro compile o código a seguir em uma biblioteca de controle de usuário. Em seguida, adicione uma referência ao arquivo de .dll compilado em um novo projeto de aplicativo Windows. Se você estiver usando Visual Studio, o ContentSerializationExampleControl será adicionado automaticamente ao Toolbox.

Arraste o controle do Toolbox para um formulário e defina as propriedades do objeto DimensionData listado no janela Propriedades. Quando você exibir o código do formulário, o código terá sido adicionado ao InitializeComponent método do formulário pai. Esse código define os valores das propriedades do controle para aqueles que você 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

Comentários

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

Com o DesignerSerializationVisibilityAttributecódigo de inicialização, você pode indicar se o valor de uma propriedade é Visiblee deve ser mantido no código Hiddende inicialização, e não deve ser mantido no código de inicialização, ou consiste, que deve ter o código de Contentinicialização gerado para cada público, não a propriedade oculta do objeto atribuído à propriedade.

Os membros que não têm um DesignerSerializationVisibilityAttribute serã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 a serialização personalizada para um determinado tipo ou propriedade, use o DesignerSerializerAttribute.

Para obter mais informações, consulte Atributos.

Construtores

Nome Description
DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility)

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

Campos

Nome Description
Content

Especifica que um serializador deve serializar o conteúdo da propriedade, em vez da própria propriedade. Este campo é somente leitura.

Default

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

Hidden

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

Visible

Especifica que um serializador deve ter permissão para serializar o valor da propriedade. Este static campo é somente leitura.

Propriedades

Nome Description
TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para esse Attribute.

(Herdado de Attribute)
Visibility

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

Métodos

Nome Description
Equals(Object)

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

GetHashCode()

Retorna o código hash deste objeto.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Obtém um valor que indica se o valor atual do atributo é o valor padrão para o atributo.

Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

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

Recupera as informações de tipo de um objeto, que podem ser usadas para obter as informações de tipo de uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

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

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

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

(Herdado de Attribute)

Aplica-se a

Confira também