Compartilhar via


NotifyParentPropertyAttribute Classe

Definição

Indica que a propriedade pai é notificada quando o valor da propriedade à qual esse atributo é aplicado é modificado. Essa classe não pode ser herdada.

public ref class NotifyParentPropertyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Property)]
public sealed class NotifyParentPropertyAttribute : Attribute
public sealed class NotifyParentPropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Property)>]
type NotifyParentPropertyAttribute = class
    inherit Attribute
type NotifyParentPropertyAttribute = class
    inherit Attribute
Public NotInheritable Class NotifyParentPropertyAttribute
Inherits Attribute
Herança
NotifyParentPropertyAttribute
Atributos

Exemplos

O exemplo de código a seguir demonstra como usar a classe e a NotifyParentPropertyAttributeExpandableObjectConverter classe para criar uma propriedade expansível em um controle personalizado.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;

namespace ExpandableObjectDemo;

public partial class DemoControl : UserControl
{
    Container components;

    public DemoControl() => InitializeComponent();

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

    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [Category("Demo")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public BorderAppearance Border { get; set; } = new();

    void InitializeComponent()
    {
        components = new Container();
        AutoScaleMode = AutoScaleMode.Font;
    }
}

[TypeConverter(typeof(BorderAppearanceConverter))]
public class BorderAppearance
{
    int borderSizeValue = 1;
    Color borderColorValue = Color.Empty;

    [Browsable(true),
    NotifyParentProperty(true),
    EditorBrowsable(EditorBrowsableState.Always),
    DefaultValue(1)]
    public int BorderSize
    {
        get => borderSizeValue;
        set
        {
            if (value < 0)
            {
                throw new ArgumentOutOfRangeException(
                    "BorderSize",
                    value,
                    "must be >= 0");
            }

            if (borderSizeValue != value)
            {
                borderSizeValue = value;
            }
        }
    }

    [Browsable(true)]
    [NotifyParentProperty(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [DefaultValue(typeof(Color), "")]
    public Color BorderColor
    {
        get => borderColorValue;
        set
        {
            if (value.Equals(Color.Transparent))
            {
                throw new NotSupportedException("Transparent colors are not supported.");
            }

            if (borderColorValue != value)
            {
                borderColorValue = value;
            }
        }
    }
}

public class BorderAppearanceConverter : ExpandableObjectConverter
{
    // This override prevents the PropertyGrid from 
    // displaying the full type name in the value cell.
    public override object ConvertTo(
        ITypeDescriptorContext context,
        CultureInfo culture,
        object value,
        Type destinationType) => destinationType == typeof(string)
            ? ""
            : base.ConvertTo(
            context,
            culture,
            value,
            destinationType);
}
Imports System.ComponentModel
Imports System.Drawing
Imports System.Globalization
Imports System.Windows.Forms

Public Class DemoControl
    Inherits UserControl

    Private borderAppearanceValue As New BorderAppearance()
    Private components As System.ComponentModel.IContainer = Nothing


    Public Sub New()
        InitializeComponent()

    End Sub

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)

        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If

        MyBase.Dispose(disposing)

    End Sub

    <Browsable(True), _
    EditorBrowsable(EditorBrowsableState.Always), _
    Category("Demo"), _
    DesignerSerializationVisibility(DesignerSerializationVisibility.Content)> _
    Public Property Border() As BorderAppearance

        Get
            Return Me.borderAppearanceValue
        End Get

        Set(ByVal value As BorderAppearance)
            Me.borderAppearanceValue = value
        End Set

    End Property

    Private Sub InitializeComponent()
        components = New System.ComponentModel.Container()
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font

    End Sub
End Class

<TypeConverter(GetType(BorderAppearanceConverter))>  _
Public Class BorderAppearance
    Private borderSizeValue As Integer = 1
    Private borderColorValue As Color = Color.Empty
    
    
    <Browsable(True), NotifyParentProperty(True), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(1)>  _
    Public Property BorderSize() As Integer 
        Get
            Return borderSizeValue
        End Get
        Set
            If value < 0 Then
                Throw New ArgumentOutOfRangeException("BorderSize", value, "must be >= 0")
            End If
            
            If borderSizeValue <> value Then
                borderSizeValue = value
            End If
        End Set
    End Property
    
    
    <Browsable(True), NotifyParentProperty(True), EditorBrowsable(EditorBrowsableState.Always), DefaultValue(GetType(Color), "")>  _
    Public Property BorderColor() As Color 
        Get
            Return borderColorValue
        End Get
        Set
            If value.Equals(Color.Transparent) Then
                Throw New NotSupportedException("Transparent colors are not supported.")
            End If
            
            If borderColorValue <> value Then
                borderColorValue = value
            End If
        End Set
    End Property
End Class

Public Class BorderAppearanceConverter
    Inherits ExpandableObjectConverter
    
    ' This override prevents the PropertyGrid from 
    ' displaying the full type name in the value cell.
    Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object

        If destinationType Is GetType(String) Then
            Return ""
        End If

        Return MyBase.ConvertTo(context, culture, value, destinationType)

    End Function
End Class

Comentários

Aplique-se NotifyParentPropertyAttribute a uma propriedade se sua propriedade pai deve receber notificação de alterações nos valores da propriedade. Por exemplo, na janela Propriedades, a DataGridView.RowTemplate propriedade tem propriedades aninhadas, como Height e DefaultCellStyle. Essas propriedades aninhadas são marcadas para NotifyParentPropertyAttribute(true) que notifiquem a propriedade pai para atualizar seu valor e exibir quando os valores da propriedade forem alterados.

Para obter mais informações sobre como usar atributos, consulte Atributos.

Construtores

Nome Description
NotifyParentPropertyAttribute(Boolean)

Inicializa uma nova instância da NotifyParentPropertyAttribute classe, usando o valor especificado para determinar se a propriedade pai é notificada de alterações no valor da propriedade.

Campos

Nome Description
Default

Indica o estado de atributo padrão, que a propriedade não deve notificar a propriedade pai de alterações em seu valor. Este campo é somente leitura.

No

Indica que a propriedade pai não é notificada de alterações no valor da propriedade. Este campo é somente leitura.

Yes

Indica que a propriedade pai é notificada de alterações no valor da propriedade. Este campo é somente leitura.

Propriedades

Nome Description
NotifyParent

Obtém ou define um valor que indica se a propriedade pai deve ser notificada de alterações no valor da propriedade.

TypeId

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

(Herdado de Attribute)

Métodos

Nome Description
Equals(Object)

Obtém um valor que indica se o objeto especificado é o mesmo que o objeto atual.

GetHashCode()

Obtém 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