DesignerSerializationVisibilityAttribute Класс

Определение

Задает тип сохранения, используемый при сериализации свойства компонента во время разработки.

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
Наследование
DesignerSerializationVisibilityAttribute
Атрибуты

Примеры

В следующем примере кода показано использование DesignerSerializationVisibilityAttribute набора для .Content Он сохраняет значения открытого свойства пользовательского элемента управления, которое можно настроить во время разработки. Чтобы использовать этот пример, сначала скомпилируйте следующий код в библиотеку пользовательских элементов управления. Затем добавьте ссылку на скомпилированный файл .dll в новый проект приложения Windows. Если вы используете Visual Studio, ContentSerializationExampleControl объект автоматически добавляется на панель элементов.

Перетащите элемент управления с панели элементов в форму и задайте свойства объекта, указанного DimensionData в окно свойств. При просмотре кода формы код будет добавлен в InitializeComponent метод родительской формы. Этот код задает значения свойств элемента управления, заданные в режиме конструктора.

#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.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

Комментарии

Когда сериализатор сохраняет сохраняемое состояние документа в режиме разработки, он часто добавляет код в метод инициализации компонентов для сохранения значений свойств, заданных во время разработки. Это происходит по умолчанию для большинства базовых типов, если ни один атрибут не был настроен для направления другого поведения.

DesignerSerializationVisibilityAttributeС помощью можно указать, является Visibleли значение свойства , и должно ли сохраняться в коде инициализации , Hiddenи не должны сохраняться в коде инициализации или состоит из Content, который должен иметь код инициализации, созданный для каждого открытого, а не скрытого свойства объекта, назначенного свойству .

Члены, у которых DesignerSerializationVisibilityAttribute нет , будут рассматриваться так, как если бы у них был DesignerSerializationVisibilityAttribute объект со значением Visible. Значения свойства, помеченного как Visible , по возможности сериализуются сериализатором для типа . Чтобы указать пользовательскую сериализацию для определенного типа или свойства, используйте DesignerSerializerAttribute.

Дополнительные сведения см. в разделе Атрибуты.

Конструкторы

DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility)

Инициализирует новый экземпляр класса DesignerSerializationVisibilityAttribute, используя указанное значение DesignerSerializationVisibility.

Поля

Content

Определяет, что средство сериализации должно сериализовать содержимое данного свойства, а не само свойство. Это поле доступно только для чтения.

Default

Задает значение по умолчанию, равное Visible, то есть в режиме визуального конструктора для создания значения свойства используются правила по умолчанию. Это статическое (static) поле доступно только для чтения.

Hidden

Определяет, что средство сериализации не должно сериализировать значение свойства. Это статическое (static) поле доступно только для чтения.

Visible

Определяет, что средству сериализации должно быть разрешено сериализировать значение свойства. Это статическое (static) поле доступно только для чтения.

Свойства

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)
Visibility

Возвращает значение, показывающее базовый режим сериализации, который должен использоваться средством сериализации при определении необходимости и способа сохранения значения свойства.

Методы

Equals(Object)

Указывает, равен ли этот экземпляр заданному объекту.

GetHashCode()

Возвращает хэш-код для этого объекта.

GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

Возвращает значение, показывающее, является ли текущее значение атрибута его значением по умолчанию.

IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

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

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

Применяется к

См. также раздел